简体   繁体   中英

Python dictionaries - difference between dict.get(key) and dict.get(key, {})

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!

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', {})
{}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM