0

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!

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
  • 10
    First method returns None if the key is not present, whereas the second method returns an empty dictionary. – Alexander Mar 18 '19 at 20:33
  • 9
    Run both on an empty dictionary and you will see. – Klaus D. Mar 18 '19 at 20:33
  • 1
    The latter is usually seen when you want to also call .get on the result again. – wim Mar 18 '19 at 20:34
  • 4
    "They seem to do the same thing" -- how so? 30 seconds of experimentation in the shell falsifies that. – John Coleman Mar 18 '19 at 20:34
  • 1
    Note the optional `value` argument in `dict.get()`: "Value to be returned if the key is not found. The default value is None." You can also pass in `'abcde'`, `5`, or a function call if you so desire – G. Anderson Mar 18 '19 at 20:37
  • To all of you who have roasted me, I agree this was a stupid question in hind sight. To those of you who answered (@wim, @Alexander, @G.Anderson), thank you! – Intrastellar Explorer Mar 18 '19 at 21:01
  • I wouldn't say it's stupid @IntrastellarExplorer There's a strong historical precedent for having a canonical answer for some simpler programming questions. See https://stackoverflow.com/questions/1003841/how-do-i-move-the-turtle-in-logo and its history https://stackoverflow.blog/2009/06/18/podcast-58/ – Conspicuous Compiler Mar 18 '19 at 21:05

2 Answers2

7

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', {})
{}
Draconis
  • 3,209
  • 1
  • 19
  • 31
2

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.

Eric Wilson
  • 57,719
  • 77
  • 200
  • 270