I have lists like:
key1=['A','B','C']
key2=['X','Y','Z']
entry1=['x1','y1','z1']
entry2=['x2','y2','z2']
entry3=['x3','y3','z3']
I want my dictionary to have items in the following format:
mydict={'A':{'X':'x1','Y':'y1','Z':'z1'},'B':{'X':'x2','Y':'y2','Z':'z2'},'C':{'X':'x3','Y':'y3','Z':'z3'}}
Can someone help??
It's easier if you start by making the three entry
lists into a single list. Then you can zip
that list with key1
to get:
entries = [entry1, entry2, entry3]
mydict = {
k1: {k2: e for k2, e in zip(key2, entry)}
for k1, entry in zip(key1, entries)
}
Here is you can use a nested dictionary comprehension:
key1=['A','B','C']
key2=['X','Y','Z']
entry1=['x1','y1','z1']
entry2=['x2','y2','z2']
entry3=['x3','y3','z3']
entries = [entry1, entry2, entry3]
my_dict = {k1:{k2:v for k2,v in zip(key2,entry)} for k1,entry in zip(key1,entries)}
print(my_dict)
Output:
{'A': {'X': 'x1', 'Y': 'y1', 'Z': 'z1'}, 'B': {'X': 'x2', 'Y': 'y2', 'Z': 'z2'}, 'C': {'X': 'x3', 'Y': 'y3', 'Z': 'z3'}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.