如何创建基于键的合并值的字典? [英] How to Create a Dictionary Merging Values Based on Keys?

查看:54
本文介绍了如何创建基于键的合并值的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个将键映射到合并值的字典。
假设我有重复的键 40 {40: lamb} {40:狗} {50:鸡}

I need to create a dictionary mapping a keys to merged values. Let's say I got key value pairs with a duplicated key 40: {40: "lamb"}, {40: "dog"}, {50: "chicken"}

list_key = (40, 40, 50)
new_value = ("lamb", "dog", "chicken")

new_dict = {}
for i in list_key:
    if i not in new_dict:
        new_dict[list_key] = new_value
    else:
        new_dict[?] = new_value

return new_dict

这就是我遇到的问题。

我需要的是 {40 :(小羊,狗),50 :(鸡)}
如何获取?

What i need is {40: ("lamb", "dog"), 50: ("chicken")}. How can I get this?

推荐答案

一种方法是在不存在键的情况下创建列表。然后,只要您遇到相关的密钥,就添加到该列表中。

One way is to create a list if the key doesn't exist. Then, just append to that list whenever you encounter a relevant key.

keys = [40, 40, 50]
values = ["lamb", "dog", "chicken"]
d = {}

for k, v in zip(keys, values):
    if k not in d:
        d[k] = []
    d[k].append(v)

...尽管您可以使用 collections.defaultdict 更简洁地完成此操作:

...Though you can do this more prettily with collections.defaultdict:

keys = [40, 40, 50]
values = ["lamb", "dog", "chicken"]
d = defaultdict(lambda: [])

for k, v in zip(keys, values):
    d[k].append(v)

这篇关于如何创建基于键的合并值的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆