![]() For example, here we demonstrate that it works for lists, sets, tuples, and arrays: Advertisements from array import arrayįavorite_foods = This consistency also extends to other built-in composed types and collections, as well as collections defined in Python standard library modules. True Using “=” for Other Python CollectionsĪs we saw, Python’s treatment of equality for dictionaries is consistent with its treatment of equality for simple types like numbers and strings. Print(type_aware_equals(dictionary, same_dictionary)) # Make sure equal dictionaries are reported correctly Print(type_aware_equals(dictionary, type_changed)) Print(type_aware_equals(dictionary, value_changed)) Print(type_aware_equals(dictionary, key_removed)) print(type_aware_equals(dictionary, key_added)) We’ll also do one more check for dictionaries we know to be equal to make sure that case works. To test this, we can run our original cases again, using the function instead of = this time. ![]() # Return early if standard equality fails """Compares dictionaries with strong check on equality of values""" Here’s one version of a method that will work: import typingĭef type_aware_equals(d1: typing.Dict, d2: typing.Dict) -> bool: If we need to check that the dictionaries are equal and that the types of all the values are equal, that’s relatively straightforward in Python. Output True What If We Need a Stronger Check for Equality? In the same way: Advertisements print(1 = 1.0) This has nothing to do with dictionaries per se - it’s just a property of the values being compared. Behind the scenes, the integer value converts to a float, the two floats are compared, and the comparison returns true. What’s happening in the last case is that we’re comparing a 1 (an integer) with 1.0 (a floating point value). Use Caution With Equality-Compatible Types The first three cases are pretty much what we’d expect. # Change type of a value from int to float Let’s see this for dictionaries: dictionary = Python is not just consistent for simple types, it also implements reasonable equality checks for more complex types as well. ![]() Of course, this also works for negative cases, as you’d expect: "pig" = "canary" returns False. In Python, in contrast, you can largely rely on = to do the right thing most of the time.Ĭonsider the following code: string = "Hello" It’s different from Java, for example, where string comparisons compare object references, and you have to use the “equals” method to do the string comparison you want to do. Two of the benefits of Python are its ease of use and consistency. Notepad++ Compare Plugin - Download, Install and (How to) Use ![]()
0 Comments
Leave a Reply. |