【问题标题】:Convert a pair of list objects into dictionary with duplicates included将一对列表对象转换为包含重复项的字典
【发布时间】:2019-05-10 08:22:44
【问题描述】:

我可以将两个列表合并到字典中,如下所示 -

list1 = [1,2,3,4]
list2 = ['a','b','c','d']
dct = dict(zip(list1, list2))
print(dct)

结果,

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

但是有如下重复,

list3 = [1,2,3,3,4,4]
list4 = ['a','b','c','d','e','f']
dct_ = dict(zip(list1, list2))
print(dct)

我明白了,

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

我应该怎么做才能将列表中的重复项视为结果字典中的单个键?

我期待结果如下 -

{1: 'a', 2: 'b', 3: 'c', 3: 'd', 4: 'e', 4: 'f'}

【问题讨论】:

  • dict 无法做到这一点。一个键最多可以出现一次。
  • @Michael Butscher 有没有其他方法可以实现这一点(列表之间的映射,无论列表中的重复项如何)?我需要在我的应用程序中使用它。
  • @Rohit 看到 YOLO 的回答。

标签: python list dictionary


【解决方案1】:

相反,您可以创建带有列表值的字典:

from collections import defaultdict
d = defaultdict(list)

for k,v in zip(list3, list4):
    d[k].append(v)

defaultdict(list, {1: ['a'], 2: ['b'], 3: ['c', 'd'], 4: ['e', 'f']})

【讨论】:

  • d[k].append(v) 会更好。照原样,您每次都用新的列表替换列表,这太过分了。
【解决方案2】:

字典中不能有重复的键。但是,您可以将多个值(一个列表)映射到每个键。

一个简单的方法是使用dict.setdefault()

list3 = [1,2,3,3,4,4]
list4 = ['a','b','c','d','e','f']

d = {}
for x, y in zip(list3, list4):
    d.setdefault(x, []).append(y)

print(d)
# {1: ['a'], 2: ['b'], 3: ['c', 'd'], 4: ['e', 'f']}

另一种选择是使用collections.defaultdict(),如@YOLO 的answer 所示。

【讨论】:

    猜你喜欢
    • 2012-09-24
    • 2016-02-16
    • 2021-06-28
    • 2014-04-02
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多