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.
>Solution :
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}]