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

Extract values by key from a nested dictionary based on specific values

I have a nested dictionary which has been extracted from a PDF userform using the PyPDF2 library.

form_dict = {'Apple': {'/FT': '/Btn', '/T': 'Apple'},
 'Banana': {'/FT': '/Btn', '/T': 'Banana', '/V': '/Yes'},
 'Grape': {'/FT': '/Btn', '/T': 'Grape', '/V': '/Yes'}
}

I want to create a list of the outer keys for which the value against the inner key ‘/V’ is equal to ‘/Yes’.

In this case the answer I am looking for is list containing ‘Banana’and ‘Grape’

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

Thanks

>Solution :

List comprehension combined with iteration over the dictionary:

[k for k, v in form_dict.items() if '/V' in v and v['/V'] == '/Yes']

Explanation: the comprehension loops over form_dict, extracting each key-value pair as k and v. Then k is included in the resulting list if v has the key ‘/V’ AND its corresponding value is ‘/Yes’.

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