How to get a value using keys in a nested dictionary in a specific context. Like as follows:
The nested dictionary is something like:
my_dict = { 'name': {0: 'alisa',1: 'monica',2: 'jessica'}, 'location': {0: 'america',1: 'canada',2: 'korea'}, 'age': {0: '22',1: '23',2: '24'}}
If the list is given with the values [0], [1], and [1], then the output has to be shown as ‘alisa’, ‘canada’ and ’23’.
Answer
You can zip the dictionary values and the list of keys to form the list:
my_dict = { 'name': {0: 'alisa',1: 'monica',2: 'jessica'}, 'location': {0: 'america',1: 'canada',2: 'korea'}, 'age': {0: '22',1: '23',2: '24'}} keys = [0,1,1] result = [d[k] for d,k in zip(my_dict.values(),keys)] # ['alisa', 'canada', '23']
Note that [0][1][1] is not a valid Python data structure. If you are receiving this as a string, you will need to convert it to a list of numbers (e.g. keys = map(int,string[1:-1].split("]["))
)