从多个列表创建字典,其中每个列表没有一个键的值,但是每个列表都有所有键的值

时间:2020-06-23 02:42:33

标签: python python-3.x

我有类似的列表:

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'}}

有人可以帮忙吗?

2 个答案:

答案 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'}}