Why is the following code true?
>>> foo = {}
>>> foo > 1
True
>>> foo < 1
False
>>> foo == 0
False
>>> foo == -1
False
>>> foo == 1
False
I understand what I wanted was len(foo) > 1, but as a beginner this surprised me.
In Python, an empty dictionary means that it does not contain key-value pair elements. In this example to create an empty dictionary, we can use a dict constructor and this method takes no arguments. If no argument is passed then it creates an empty dictionary.
# Checking if a dictionary is empty by checking its length empty_dict = {} if len(empty_dict) == 0: print('This dictionary is empty! ') else: print('This dictionary is not empty! ') # Returns: This dictionary is empty!
If the dictionary is empty, it returns None which is not == False . Your if statement is backwards.
To get the value for the key, use dict[key] . dict[key] raises an error when the key does not exist, but the get() method returns a specified value (default is None ) if the key does not exist.
From the docs:
The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-builtin types by defining a
__cmp__
method or rich comparison methods like__gt__
, described in section 3.4.(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)
rich comparison between incompatible types is based on the name(?) of the type in python2.x and has been disallowed in python3.x.
In any event, in python2.x, the ordering is guaranteed to give the same results for a particular python implementation and version, but the ordering itself is not defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With