python - 来自两个列表的字典,包括键的多个值

标签 python dictionary

是否有可能从两个具有相同键的列表创建字典而不遍历整个数据集?

最小的例子:

keys = [1, 2, 3, 2, 3, 4, 5, 1]
values = [1, 2, 3, 4, 5, 6, 7, 8]

# hoped for result:
dictionary = dict(???)
dictionary = {1 : [1,8], 2:[2,4], 3:[3,5], 4:[6], 5:[7]}

当使用 zip 时,插入的键值对会覆盖旧的:

dictionary = dict(zip(keys,values))
dictionary = {1: 8, 2: 4, 3: 5, 4: 6, 5: 7}

我也会对 Multidict 感到满意。

最佳答案

这是一种不需要 2 个 for 循环的方法

h = defaultdict(list)
for k, v in zip(keys, values):
    h[k].append(v)

print(h)
# defaultdict(<class 'list'>, {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]})

print(dict(h))
# {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]}


关于python - 来自两个列表的字典,包括键的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038406/

相关文章:

python - 我可以在使用 aws_cdk 创建 lambda 后立即调用它吗?

python - 遍历日历月的开始/结束

python - 返回 bool 值列表,比较 Pandas 中列表的行

iphone - 直接访问 Objective-C 中的嵌套字典值

arrays - 在 Swift 中轻松访问和修改字典数组

python - 通过 AdminSite.get_urls 添加非基于模型的 URL 不起作用

python - 从 Python 中缺失值的 DataFrame 创建系列

c - 在字典中查找单词 C 编程

python - 通过在 python 中取平均值来生成 dict

google-maps - 如何使用 GMaps.js 的 fitBounds