Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find a dictionary that meets certain criteria and return a value from it

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading