jugovich
jugovich

Reputation: 123

Python using dict .get() method where value = 0

(Python 2.7.2) I would like to better understand why the default value is returned when using a dictionaries .get() method to find a key when the value mapped to the key is 0.

Consider the following

x = {1:0}

print x.get('1', 'a')

'a'

The same happens for an empty string, set, etc.

but if I do:

print x[1]
0

Does the .get() method return the default value both when a keyError is raised and if the value returned is 0 or an empty set?

Is it has something to do with the fact that the dict object is immutable and that when I point to the value stored on key = 1, I am getting passed a reference to a object that equates to False.

I know I could write my own get method that does a

def get(key, default=None):
    try: return x[key]
    except KeyError: return default

but I would like to have a more in depth understanding of the .get method.

Upvotes: 3

Views: 9232

Answers (2)

bradley.ayers
bradley.ayers

Reputation: 38382

You made mistake in your first experiment:

>>> x = {1: 0}
>>> x.get('1', 'a')
'a'
>>> x.get(1, 'a')
0

In Python, dict keys can be any hashable type, not just strings.

Upvotes: 4

DSM
DSM

Reputation: 353179

1 != '1'; an int isn't equal to a str.

>>> x = {1:0}
>>> 
>>> print x.get('1', 'a')
a
>>> print x.get(1, 'a')
0

Upvotes: 10

Related Questions