使用字典理解将列表转换为具有重复键的字典 [英] Convert list to dictionary with duplicate keys using dict comprehension

查看:82
本文介绍了使用字典理解将列表转换为具有重复键的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在尝试使用以下内容将长度为 2 的项目列表转换为字典:

I am trying to convert a list of length-2 items to a dictionary using the below:

my_list = ["b4", "c3", "c5"]
my_dict = {key: value for (key, value) in my_list}

问题是当列表中出现多个键时,只保留最后一个键及其值.

The issue is that when a key occurrence is more than one in the list, only the last key and its value are kept.

所以在这种情况下而不是

So in this case instead of

my_dict = {'c': '3', 'c': '5', 'b': '4'}

我明白了

my_dict = {'c': '5', 'b': '4'}

即使有重复的键,我如何保留所有键:值对.谢谢

How can I keep all key:value pairs even if there are duplicate keys. Thanks

推荐答案

对于字典中的一个键,您只能存储一个值.

For one key in a dictionary you can only store one value.

您可以选择将值作为列表.

You can chose to have the value as a list.

{'b': ['4'], 'c': ['3', '5']}

以下代码将为您做到这一点:

following code will do that for you :

new_dict = {}
for (key, value) in my_list:
    if key in new_dict:
        new_dict[key].append(value)
    else:
        new_dict[key] = [value]
print(new_dict)
# output: {'b': ['4'], 'c': ['3', '5']}

同样的事情可以用 setdefault 来完成.感谢@Aadit M Shah 指出

Same thing can be done with setdefault. Thanks @Aadit M Shah for pointing it out

new_dict = {}
for (key, value) in my_list:
    new_dict.setdefault(key, []).append(value)
print(new_dict)
# output: {'b': ['4'], 'c': ['3', '5']}

同样的事情可以用 defaultdict 来完成.感谢@MMF 指出.

Same thing can be done with defaultdict. Thanks @MMF for pointing it out.

from collections import defaultdict
new_dict = defaultdict(list)
for (key, value) in my_list:
    new_dict[key].append(value)
print(new_dict)
# output: defaultdict(<class 'list'>, {'b': ['4'], 'c': ['3', '5']})

您还可以选择将值存储为字典列表:

you can also chose to store the value as a list of dictionaries:

[{'b': '4'}, {'c': '3'}, {'c': '5'}]

以下代码将为您做到这一点

following code will do that for you

new_list = [{key: value} for (key, value) in my_list]

这篇关于使用字典理解将列表转换为具有重复键的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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