如何向python中的字典键添加多个值? [英] How to add multiple values to a dictionary key in python?

查看:69
本文介绍了如何向python中的字典键添加多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向 Python 字典中的特定键添加多个值.我该怎么做?

a = {}a[abc"] = 1a[abc"] = 2

这会将 a[abc"] 的值从 1 替换为 2.

我想要的是 [abc"] 具有多个值(1 和 2).

解决方案

将值设为列表,例如

a["abc"] = [1, 2, "bob"]

更新:

有几种方法可以将值添加到键,并在没有列表的情况下创建列表.我将逐步展示一种这样的方法.

key = "somekey"a.setdefault(key, [])a[key].append(1)

结果:

<预><代码>>>>一个{'somekey':[1]}

接下来,尝试:

key = "somekey"a.setdefault(key, [])a[key].append(2)

结果:

<预><代码>>>>一个{'somekey': [1, 2]}

setdefault 的神奇之处在于它初始化该键的值 如果 该键未定义,否则它什么都不做.现在,请注意 setdefault 返回键,您可以将它们组合成一行:

a.setdefault("somekey",[]).append("bob")

结果:

<预><代码>>>>一个{'somekey': [1, 2, 'bob']}

您应该查看 dict 方法,尤其是 get() 方法,并进行一些实验以适应这一点.

I want to add multiple values to a specific key in a python dictionary. How can I do that?

a = {}
a["abc"] = 1
a["abc"] = 2

This will replace the value of a["abc"] from 1 to 2.

What I want instead is for a["abc"] to have multiple values(both 1 and 2).

解决方案

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

这篇关于如何向python中的字典键添加多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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