Home > Enterprise >  Extract values by key from a nested dictionary based on specific values
Extract values by key from a nested dictionary based on specific values

Time:04-11

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'

Thanks

CodePudding user response:

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'.

  • Related