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

Time:07-17

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']?

CodePudding user response:

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']

CodePudding user response:

You can use the below code if you want the list of event_id

[v2['event_id'] for k1, v1 in Data.items() for k2, v2 in v1['event_dict'].items()]

CodePudding user response:

mylist=[] 
for k1,v1 in Data.items():
    print('MAIN entity:',k1)
    for k2,v2 in Data[k1].items():
         if k2=='event_dict':
            # print(k2,v2)
            for k3,v3 in Data[k1][k2].items():
                print(k3,v3['event_id']) 
                
print("-------------------OR-------------")    
for k1,v1 in Data.items():
    
    for k2,v2 in Data[k1].items():
         if k2=='event_dict':
            # print(k2,v2)
            for k3,v3 in Data[k1][k2].items():
                print(v3['event_id'],sep=" ",) 
                mylist.append(v3['event_id'])
    print(mylist)

              
  • Related