我有类似的列表:
key1=['A','B','C']
key2=['X','Y','Z']
entry1=['x1','y1','z1']
entry2=['x2','y2','z2']
entry3=['x3','y3','z3']
我希望我的字典中的项目具有以下格式:
mydict={'A':{'X':'x1','Y':'y1','Z':'z1'},'B':{'X':'x2','Y':'y2','Z':'z2'},'C':{'X':'x3','Y':'y3','Z':'z3'}}
有人可以帮忙吗?
答案 0 :(得分:0)
如果先将三个entry
列表合并为一个列表,则会更容易。然后,您可以使用zip
key1
来获得该列表:
entries = [entry1, entry2, entry3]
mydict = {
k1: {k2: e for k2, e in zip(key2, entry)}
for k1, entry in zip(key1, entries)
}
答案 1 :(得分:0)
这是您可以使用嵌套字典理解的方法:
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)
输出:
{'A': {'X': 'x1', 'Y': 'y1', 'Z': 'z1'}, 'B': {'X': 'x2', 'Y': 'y2', 'Z': 'z2'}, 'C': {'X': 'x3', 'Y': 'y3', 'Z': 'z3'}}