Python: zip 2 lists into a dictionary, 删除重复键但保留值

Python: zip 2 lists into a dictonary, del the duplicated keys but keep the values

我是 Python 的新手。我正在尝试将 2 个列表压缩到字典中而不丢失重复键的值,并将值作为列表保存在字典中。

示例:

list1 = [0.43, -1.2, 50, -60.5, 50]

list2 = ['tree', 'cat', 'cat', 'tree', 'hat']

我正在尝试获得以下结果:

{'tree': [0.43, -60.5],'cat': [-1.2, 50],'hat': [50]}

感谢您的帮助。

可以使用字典的setdefault方法:

list1 = [0.43, -1.2, 50, -60.5, 50]
list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
d = {}
for k, v in zip(list2, list1):
    d.setdefault(k, []).append(v)

结果:

>>> d
{'cat': [-1.2, 50], 'hat': [50], 'tree': [0.43, -60.5]}

Mike Muller 提供的答案非常有效。另一种可能稍微更 pythonic 的方法是使用集合库中的 defaultdict

from collections import defaultdict

list1 = [0.43, -1.2, 50, -60.5, 50]
list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
d = defaultdict(list)
for k, v in zip(list2, list1):
    d[k].append(v)

只是为了完整起见,这就是我在早期编程时的做法

>>> list1 = [0.43, -1.2, 50, -60.5, 50]
>>> list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
>>> result=dict()
>>> for k,v in zip(list2,list1):
        if k in result:
            result[k].append(v)
        else:
            result[k]=[v]


>>> result
{'hat': [50], 'tree': [0.43, -60.5], 'cat': [-1.2, 50]}
>>>