Python Forum
Searching for nested items within the dictionary data structure
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Searching for nested items within the dictionary data structure
#11
I just wanted to pinpoint that there are subtle differences between accessing dict value by key or by .get method.

>>> d = dict(enumerate('abc'))
>>> d
{0: 'a', 1: 'b', 2: 'c'}
>>> d[0]
'a'
>>> d.get(0)
'a'
>>> d[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 3
>>> d.get(3)
>>>
If key not in the dict .get method doesn't rise KeyError, it returns default value.

>>> help(dict.get)
Help on method_descriptor:

get(self, key, default=None, /)
    Return the value for key if key is in the dictionary, else default.
rob101 likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020