Home > front end >  Extract values from a particular key in a nested dictionary
Extract values from a particular key in a nested dictionary

Time:04-04

I'm stuck on this problem where I have to extract values of a particular key in nested dictionaries

my dictionary is:

my_dict = {'Usama': {'connected': ['Saeed', 'Aaliya', 'Mohsin']}}

and I need all the values of "connected" in a single list when the user enters "Usama"

CodePudding user response:

you can use

name = "usama"
my_dict[name]["connected"]

if you want, you can use variable inside square brackets to access

I hope it will help you

CodePudding user response:

If you understand the schema of the JSON/dictionary, you can just easily loop over it:

my_dict = {'Usama': {'connected': ['Saeed', 'Aaliya', 'Mohsin']},
           'Joe':   {'connected': ['Ashley', 'Tom']}
}
for person, values in my_dict.items():
    print(f"Looping over {person} data")
    for status, connections in values.items():
        print(f"{person}'s status is '{status}' with {', '.join(connections)}")

If you want to break when the user is "Usama", you can do something like this:

for person, values in my_dict.items():
    print(f"Looping over {person} data")
    for status, connections in values.items():
        print(f"{person}'s status is '{status}' with {', '.join(connections)}")
    if person == 'Usama':
        break
     
print(connections)

This prints out:

Looping over Usama data
Usama's status is 'connected' with Saeed, Aaliya, Mohsin
['Saeed', 'Aaliya', 'Mohsin']

It just depends on what you're trying to do. If you have a list of names you're interested about, just use that instead of looping over the whole dictionary, since that's not what they are intended for.

Ex:

people_of_interest = ['Usama']
for interested_name in people_of_interest:
    if interested_name in my_dict:
        print(my_dict[interested_name]['connected'])
  • Related