首页 > 解决方案 > 在字典中组合两个列表保留具有多个值的键的重复值

问题描述

我想将两个列表组合成一个字典,但保留每个键的所有值。查看我想要的输出:

Two lists:
a = ['E', 'AA', 'AA','AA', 'S', 'P']
b = ['11', '22', '33','44', '55', '66']

Output is a dictionary:
dict_1 = {'E': ['11'], 'AA': ['22', '33', '44'], 'S': ['55'], 'P': ['66']}

问题

我有以下代码,经过多次尝试,我仍然只得到一个不想要的输出,如下所示(我已经尝试了一个下午):

Current undesired output:
dict_1 = {'E': ['11'], 'AA': ['44'], 'S': ['55'], 'P': ['66']}

我的代码:

a = ['E', 'AA', 'AA','AA', 'S', 'P']
b = ['11', '22', '33','44', '55', '66']
c = []
dict_1 = {}
i = 0
while i < 6:  
    j = i
    c = []
    while i<= j <6:        
        if a[i]==a[j]:
            c.append(b[j])             
        j+=1    
    dict_1[a[i]] = c
#    print(dict_1)
    i+=1        
print(dict_1)

Python 新手,在编码方面没有什么优雅之处。我只想更新它,以便获得所需的输出。如果有人对此有提示,请随时发表评论或回答。谢谢!

标签: python-3.xlistdictionary

解决方案


您可以使用dict.setdefault

a = ["E", "AA", "AA", "AA", "S", "P"]
b = ["11", "22", "33", "44", "55", "66"]

dict_1 = {}
for i, j in zip(a, b):
    dict_1.setdefault(i, []).append(j)

print(dict_1)

印刷:

{'E': ['11'], 'AA': ['22', '33', '44'], 'S': ['55'], 'P': ['66']}

推荐阅读