1

I have a dictionary containing a list of dictionaries. The number of dictionaries in the list could be infinite or could be 0 (not present at all), and the keys for these dictionaries will typically be identical, but with differing values. In the dict below, how best could I access the dict that contains "type : web" and, if present, return the value of the "id" key in that same dictionary?

{'accounts': [{'id': 'test#11882',
                         'name': 'test#11882',
                         'type': 'net',
                         'verified': False},
                        {'id': '99999',
                         'name': 'test999',
                         'type': 'web',
                         'verified': False}],
}

I considered indexing, however the dictionaries may be in any order and the "type : web" entry may not be present in any dictionary at all. I assume I'll need to iterate through the contents of "accounts," but I'm unsure how to verify the presence of a dict with "type : web" and then return the separate "id : x" entry in that dict.

Chris
  • 26,361
  • 5
  • 21
  • 42

2 Answers2

2

You might use next with a generator expression that filters your data.

>>> data = {
...   'accounts': [
...     {
...       'id': 'test#11882',
...       'name': 'test#11882',
...       'type': 'net',
...       'verified': False
...     },
...     {
...       'id': '99999',
...       'name': 'test999',
...       'type': 'web',
...       'verified': False
...     }
...   ],
... }
>>> next(
...   (x 
...    for x in data['accounts'] 
...    if x.get('type') == 'web'), 
...   dict()
... ).get('id')
'99999'

This will get the 'id' of the first dictionary that matches. If you wanted to get all matching dictionaries a list comprehension would work nicely.

>>> [x for x in data['accounts'] if x.get('type') == 'web']
[{'id': '99999', 'name': 'test999', 'type': 'web', 'verified': False}]
Chris
  • 26,361
  • 5
  • 21
  • 42
2

You can use something like this

def get_dict_id(my_dict, key):
    for d in my_dict['accounts']:
        if d['type'] =='web':
            return d['id']
    
my_dict = {'accounts': [{'id': 'test#11882',
                     'name': 'test#11882',
                     'type': 'net',
                     'verified': False},
                    {'id': '99999',
                     'name': 'test999',
                     'type': 'web',
                     'verified': False}],
}

print(get_dict_id(my_dict, 'web'))
David Sidarous
  • 1,202
  • 1
  • 10
  • 25