Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an empty dictionary greater than 1?

Tags:

python

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.

like image 393
Sean Hayden Avatar asked Jun 24 '13 20:06

Sean Hayden


People also ask

Can dictionary have empty values?

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.

How do you check if a dictionary is empty?

# 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!

Is an empty dictionary none?

If the dictionary is empty, it returns None which is not == False . Your if statement is backwards.

How do I know if a dictionary key has no value?

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.


2 Answers

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.)

like image 157
Chas. Owens Avatar answered Oct 27 '22 20:10

Chas. Owens


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.

like image 34
mgilson Avatar answered Oct 27 '22 21:10

mgilson