Home > database >  How can I append the list as a value to python dictionary
How can I append the list as a value to python dictionary

Time:08-11

I have a list as follows

[
 {A:a,B:b,C:c},
 {D:d,E:e,F:f}
]

I want the dictionary to be

{
A:{
A:a,B:b,C:c
},
D:{
D:d,E:e,F:f
}
}

CodePudding user response:

try this:

returned_dict={} 
L=[
 {'A':'a','B':'b','C':'c'},
 {'D':'d','E':'e','F':'f'}
]
for item in L:
    returned_dict[sorted(item)[0]]=item

CodePudding user response:

Use this:

l = [{'A':'a', 'B':'b', 'C':'c'},
     {'D':'d', 'E':'e', 'F':'f'}]

d = {}
for dct in l:
    d[next(iter(dct))] = dct

print(d)

Output:

{'A': {'A': 'a', 'B': 'b', 'C': 'c'},
 'D': {'D': 'd', 'E': 'e', 'F': 'f'}}
  • Related