python-3.x - 在字典中组合两个列表保留具有多个值的键的重复值
问题描述
我想将两个列表组合成一个字典,但保留每个键的所有值。查看我想要的输出:
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']}
推荐阅读
- gradle - Gradle:如何停止发布并显示错误消息
- c++ - 关键字自动和模板
- python - How to find URL between two dates in python
- mysql - MySQL Group Replication Primary ID is not continuous?
- html - 构建水平时间线 - 项目未对齐
- python - check start and end available in data using python pandas
- python - Jsonpickle - ensure deterministic encoding
- reactjs - IsValidated not working with redux in react stepzilla
- javascript - 使用 flexslider 循环遍历数组
- python - How to loop through all the pages while scraping hundreds of pages on LinkedIn?