Home > Mobile >  How to get inner key in Python dictionary
How to get inner key in Python dictionary

Time:12-14

Am I able to get the inner value by key due to some function like get. Simple dict:

dict1 = {
    'key1': 'asdfasdf'
}

If I want to get the value by key1 I just write dict1.get('key1') But what if I have such dict:

dict2 = {
    'some_key': {
        'key1': 'asdfasdf'
    }
}

How can I get value by key1 like dict2.get('key1')?

As you can understand I just need these both types of dictionaries, so I don't need dict2['some_key']['key1']

CodePudding user response:

That's a nested Dictionary

you can use iterated comprehension if you want to avoid using keys of top level dictionary to access inner items

e.g.

[p_info.get('key1') for p_id, p_info in dict2.items()]

or using just values

[p_info.get('key1') for p_info in dict2.values()]

this will return a list of asdfasdf

CodePudding user response:

If you're looking for the value associated with the first occurrence of 'key1' in a nested dictionary, a little bit of recursion can get you there.

def first(d, k):
  if k in d: return d[k]
  for v in d.values():
    if isinstance(v, dict): 
      v2 = first(v, k)
      if v2: return v2
  • Related