Reputation: 2381
When getting values from a dictionary, I have seen people use two methods:
dict.get(key)
dict.get(key, {})
They seem to do the same thing. What is the difference, and which is the more standard method?
Thank you in advance!
Upvotes: 0
Views: 803
Reputation: 59335
From the documentation:
get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
The typical way to look things up in a dictionary is d[key]
, which will raise KeyError
when the key is not present.
When you don't want to search for documentation, you can do:
d = {}
help(d.get)
which will display the docstring for the the get
method for dictionary d
.
Upvotes: 2
Reputation: 3461
The second parameter to dict.get
is optional: it's what's returned if the key isn't found. If you don't supply it, it will return None
.
So:
>>> d = {'a':1, 'b':2}
>>> d.get('c')
None
>>> d.get('c', {})
{}
Upvotes: 7