Home > Software engineering >  nested dictionary how to create key and value as nested dictionary value as value .please help me
nested dictionary how to create key and value as nested dictionary value as value .please help me

Time:10-26

check = {'Test_Category': {0: 'right', 1: 'wrong'}, 'arg1': {0: 'test2', 1: 'test12'},
         'arg2': {0: 'test4', 1: 'test41'}, 'arg3': {0: 'test5', 1: 'test55'},
         'arg4': {0: 'test6', 1: 'test67'}}

I want expected result:

[{'Test_category': 'right', 'arg1': 'test2', 'arg2': 'test4', 'arg3': 'test5','arg4':'test6'}, 
{'Test_category': 'wrong', 'arg1': 'test12', 'arg2': 'test41', 'arg3': 'test55','arg4':'test67'}]

CodePudding user response:

Here, let's try to iterate check. We'll take two empty dicts d1 and d2 in which we can add the values. d1 for values of "0"s and d2 for values of "1"s. While iteration, we'll iterate the values which itself is dict and add it accordingly. Your code:

check = {'Test_Category': {0: 'right', 1: 'wrong'}, 'arg1': {0: 'test2', 1: 'test12'},
     'arg2': {0: 'test4', 1: 'test41'}, 'arg3': {0: 'test5', 1: 'test55'},
     'arg4': {0: 'test6', 1: 'test67'}}
d1={}
d2={}
for i in check:                #values of check[i] is itself a dict, we need value of 0 key and 1 key of inner dict
    d1[i]=check[i][0]       #values of 0 of inner dict and adding it to d1
for i in check:
    d2[i]=check[i][1]       #values of 1 of inner dict and adding it to d2

l=[d1,d2]         #list of d1 and d2
print(l)        #printing l
  • Related