Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate nested dictionary and get all values of one entity

Data={
    0:{
        'name': "John",
        'country': "xyz",
        'country_id': "0",
        'event_dict': {
           0: {
               'event1': "T",
               'event_no': "45",
               'event_id': "01"
           },
           1: {
               'event1': "C",
               'event_no': "32",
               'event_id': "T",
           },    
           2: {
              'event1': "B",
              'event_no': "11",
              'event_id': "s",
           },    
           3: {
              'event1': "A",
              'event_no': "0",
              'event_id':"p",
           }
        },      
    },    
   1:{        
       'name': "Henry",
       'country': "",
       'country_id': "1",    
       'event_dict': {
           0:{
              'event1': "no",
              'event_no': "23",
              'event_id':"abc"
           },
           1: {
              'event1': "yes",
              'event_no': "8",
              'event_id':"def",
           },    
           2: {
              'event1': "false",
              'event_no': "",
              'event_id': "ghi",
           },    
           3: {
              'event1': "NA",
              'event_no': "9",
              'event_id': "jkl", 
           }
        },
    },
}

I am unable to iterate over the nested dictionary to get all the values of event_id for event_dict [0,1,2,3] for each Data[0 and 1]. How to get all the values of ['event_id']?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Try this:

for k1,v1 in Data.items():
    for k2, v2 in v1['event_dict'].items():
        print(f"{k1}->{k2}-> event_id : {v2['event_id']}")

0->0-> event_id : 01
0->1-> event_id : T
0->2-> event_id : s
0->3-> event_id : p
1->0-> event_id : abc
1->1-> event_id : def
1->2-> event_id : ghi
1->3-> event_id : jkl

Update: Store in a list.

ids = [v2['event_id'] 
       for k1,v1 in Data.items() 
       for k2, v2 in v1['event_dict'].items()]
print(ids)
# ['01', 'T', 's', 'p', 'abc', 'def', 'ghi', 'jkl']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading