0

We know how to use get with a dict in python:

a={'k':'thevalue}
a.get('k', 'There is no such key in the dict')
a.get('m', 'There is no such key in the dict')

the first one get returns the corresponding value and the second one the default value.

How would you go about the following situation in one liner:

a={'k':{'first':'uno','second':'dos'}}
# this is peseudocode:
a.get('k.first', 'There is no such key in the dict')
a.get('k["first"]', 'There is no such key in the dict')

meaning if k exists in the dict I want the content of the key value first, i.e. 'uno'.

martineau
  • 119,623
  • 25
  • 170
  • 301
JFerro
  • 3,203
  • 7
  • 35
  • 88
  • 3
    `a.get('k', {}).get('first', 'no')`. But that really depends on what keys you do expect and allow to be absent and which not. At some point, `try: a['k']['first'] except KeyError:` becomes easier and more sensible. – deceze Jun 16 '21 at 13:17
  • How about chain gets? `a.get('k').get('x', 'whatever')` – kakou Jun 16 '21 at 13:17
  • 1
    Does this answer your question? [Safe method to get value of nested dictionary](https://stackoverflow.com/questions/25833613/safe-method-to-get-value-of-nested-dictionary) – MisterMiyagi Jun 16 '21 at 13:17
  • @Karolos `AttributeError: NoneType has no .get`… – deceze Jun 16 '21 at 13:18
  • Yap I did not add a default for the first level. You can do as you said in your comment. It was just a sample of chain gets – kakou Jun 16 '21 at 13:21

0 Answers0