Python 如何在循环中增加字典的值(而不是更新它)?

Python 如何在循环中增加字典的值(而不是更新它)?,python,dictionary,Python,Dictionary,这是我的代码: diction = {} for i in range (5): key = "key" diction[key] = {str(i)} print (diction) 显然,打印的结果是: {'key': {'4'}}. 如何更改代码以便将其作为输出: {'key': {'0','1','2','3','4'}} .add()到集合中 diction = {'key': set()} for i in range(5): d

这是我的代码:

diction = {}

for i in range (5):
    key = "key"
    diction[key] = {str(i)}
print (diction)
显然,打印的结果是:

{'key': {'4'}}.
如何更改代码以便将其作为输出:

{'key': {'0','1','2','3','4'}}
.add()
到集合中

diction = {'key': set()}

for i in range(5):
    diction['key'].add(str(i))

print(diction['key'])

编辑

diction = {}

for i in range(5):
    k = 'key'+str(i*2)
    if not k in diction:
        diction[k] = set()
    
    diction[k].add(str(i))

print(diction)
列表理解应该更好:

diction = {'key': set(map(str,range(5)))}

要向集合添加值,应使用
.add
方法。对于初始情况(i=1),您还应该检查字典中是否设置了密钥,这样您就不会添加到不存在的集合中并得到错误:

因此,您的新代码将是:

diction = {}

for i in range (5):
    key = "key"
    if key not in diction:
        diction[key] = {i}
    else:
        diction[key].add(i)
结果:

print (diction)
现在是

{'key': {0, 1, 2, 3, 4}}

在Python中,最常用的两种方法可能是使用
dict.setdefault()
方法或
collections.defaultdict
字典子类

这两种方法都可以轻松修改现有条目的值,而无需检查是否是第一次看到该键。下面是两种方法的示例

setdefault()
defaultdict

非常感谢你。如果钥匙也在未定中怎么办?假设密钥是i*2(这意味着我们将有密钥和值)太棒了!谢谢大家!@欢迎光临。如果有效,请单击大复选标记接受答案!非常感谢。我发现“'dict'对象没有属性'add'”错误。在添加到字典中的集合之前,是否确保访问了正确的键
diction[key].add(str(i))
将添加到词典中的set,而
diction.add(str(i))
将尝试直接添加到词典中,这将产生您所说的错误。
diction = {}

for i in range (5):
    key = "key"
    diction.setdefault(key, set()).add(str(i))

print(diction)
from collections import defaultdict

diction = defaultdict(set)

for i in range (5):
    key = "key"
    diction[key].add(str(i))

print(diction)