python-3.x - 合并字典中的两个列表,保留具有多个值的键的重复值

标签 python-3.x list dictionary

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

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/

相关文章:

python - 将 GMT 时间戳转换为 Pandas 中的时间戳

python - pandas + bokeh - 如何获取悬停工具的数据框列名称

python列表转换为表格

python - 如何在 Python 中输入矩阵(二维列表)?

python - 如何让 Python 区分相等的整数

python - 使用 numpy.savez() 保存标题信息字典

c# - 在字典中查找最匹配的单词

python - 通过python从名称列表中提取最后两个字母

启动 MPV 的 Python 脚本

java - 如何从数组中查找项目并将其添加到列表中 (Java)