[英]create dictionary from multiple lists, where each list has not the values for one key, but each list has values for all keys
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.如果您从将三个entry
列表变成一个列表开始,会更容易。 Then you can zip
that list with key1
to get:然后你可以用key1
列出zip
得到:
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: Output:
{'A': {'X': 'x1', 'Y': 'y1', 'Z': 'z1'}, 'B': {'X': 'x2', 'Y': 'y2', 'Z': 'z2'}, 'C': {'X': 'x3', 'Y': 'y3', 'Z': 'z3'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.