我想将两个列表组合成一个字典,但保留每个键的所有值。查看我想要的输出:
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 新手,编码没什么优雅之处。我只想更新它以便获得我想要的输出。 如果有人对此有任何提示,请随时发表评论或回答。谢谢!
最佳答案
您可以使用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']}
关于python-3.x - 合并字典中的两个列表,保留具有多个值的键的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67303932/