Home > OS >  How to access a key within a nested dictionary(in a list that has dictionary)
How to access a key within a nested dictionary(in a list that has dictionary)

Time:07-11

I am very new to coding and I am trying to access a key(such as 'name') that is within a nested dictionary that has a list which holds all of the Dictionaries.

Ex. I want to access the Sex of the dictionary of people.

This is the code:

people = {1: [{"name": 'John'}, {'Age': '27'}, {'Sex': 'Male'}],
          2: [{"name": 'Marie'}, {'Age': '22'}, {'Sex': 'Female'}],
              }

for i, x in people.items():
    Accessing_People_List = people[i]
    print(people[i])
    print(type(people[i]))
    print(Accessing_People_List[i])

So far I could only access till the list part, after that everything went as well as a cook trying to do surgery on a live person.(no offense)

So could yall give me some or any suggestions on accessing it and explain how that code to does that? (cause this is some sort of a practice for myself ) GLHF.

TL;DR: need help to access a key of a nested dictionary with a list that holds several dictionaries Edit: Btw, thanks for asking

CodePudding user response:

The reason why you are having such problems is because your object structure makes no sense. Your inner lists contains 3 separate dictionaries with single key each. Drop the lists, make them 1 dictionary. -

1: {"name": 'John', 'Age': '27', 'Sex': 'Male'}

Now you can access it like this: people[1]["Sex"]. Or even better make name the key:

people = {"John": {'Age': '27', 'Sex': 'Male'},
          "Marie": {'Age': '22', 'Sex': 'Female'},
              }

print(people["John"]["Sex"])

Should you want to get it from your structure, you'd have to do something like this:

people[1][2]['Sex']

2 shows up because it dictionary that contains this info is index 2 element of the list.

CodePudding user response:

There's multiple ways to achieve this. I'm sure this question has already been answered in this thread: Safe method to get value of nested dictionary

One way is to chain gets, another is to use reduce and put this in a deep_get function so you can do this in a generic way. All of this you can find in the above link! Good luck!

CodePudding user response:

Assuming your dict is given and that you cannot change it by hand, you could do something like this to get the desired structure and then access each key:

from collections import ChainMap

people = {1: [{"name": 'John'}, {'Age': '27'}, {'Sex': 'Male'}],
          2: [{"name": 'Marie'}, {'Age': '22'}, {'Sex': 'Female'}],
              }

new_dict = {key: dict(ChainMap(*people[key])) for key in people}

new_dict[1]["Sex"] # -> 'Male'

If you do not want to import ChainMap, you can also use the following:

people = {1: [{"name": 'John'}, {'Age': '27'}, {'Sex': 'Male'}],
          2: [{"name": 'Marie'}, {'Age': '22'}, {'Sex': 'Female'}],
              }

new_dict = {key: {k:v for d in people[key] for k, v in d.items()} for key in people}

new_dict[1]["Sex"] # -> 'Male'
  • Related