'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'
Thanks
Solution 1:[1]
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'.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
