如何向现有词典中添加关键字?它没有.add()方法。


当前回答

我认为指出Python的集合模块也很有用,它由许多有用的字典子类和包装器组成,简化了字典中数据类型的添加和修改,特别是defaultdict:

调用工厂函数以提供缺失值的dict子类

如果您使用的字典总是由相同的数据类型或结构组成,例如列表字典,那么这尤其有用。

>>> from collections import defaultdict
>>> example = defaultdict(int)
>>> example['key'] += 1
>>> example['key']
defaultdict(<class 'int'>, {'key': 1})

如果键还不存在,defaultdict会将给定的值(在我们的例子中为10)作为初始值分配给字典(通常在循环中使用)。因此,此操作执行两件事:它向字典中添加一个新键(根据问题),如果键还不存在,则分配值。对于标准字典,当+=操作试图访问一个尚不存在的值时,这可能会引发错误:

>>> example = dict()
>>> example['key'] += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key'

如果不使用defaultdict,添加新元素的代码量会更大,可能看起来像:

# This type of code would often be inside a loop
if 'key' not in example:
    example['key'] = 0  # add key and initial value to dict; could also be a list
example['key'] += 1  # this is implementing a counter

defaultdict还可以用于复杂的数据类型,例如列表和集合:

>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})

添加元素会自动初始化列表。

其他回答

要同时添加多个键,请使用dict.update():

>>> x = {1:2}
>>> print(x)
{1: 2}

>>> d = {3:4, 5:6, 7:8}
>>> x.update(d)
>>> print(x)
{1: 2, 3: 4, 5: 6, 7: 8}

对于添加单个密钥,接受的答案具有较少的计算开销。

这是我在这里没有看到的另一种方式:

>>> foo = dict(a=1,b=2)
>>> foo
{'a': 1, 'b': 2}
>>> goo = dict(c=3,**foo)
>>> goo
{'c': 3, 'a': 1, 'b': 2}

可以使用字典构造函数和隐式扩展来重建字典。此外,有趣的是,这种方法可以用于控制字典构建期间的位置顺序(Python 3.6之后)。事实上,Python 3.7和更高版本保证了插入顺序!

>>> foo = dict(a=1,b=2,c=3,d=4)
>>> new_dict = {k: v for k, v in list(foo.items())[:2]}
>>> new_dict
{'a': 1, 'b': 2}
>>> new_dict.update(newvalue=99)
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99}
>>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
>>> 

以上是使用字典理解。

这个问题已经得到了令人恶心的回答,但自从我议论获得了很大的牵引力,以下是答案:

添加新密钥而不更新现有字典

如果您在这里试图找出如何添加键并返回新字典(而不修改现有字典),可以使用以下技术来完成

Python>=3.5

new_dict = {**mydict, 'new_key': new_val}

Python<3.5

new_dict = dict(mydict, new_key=new_val)

注意,使用这种方法,您的密钥需要遵循Python中有效标识符名称的规则。

我想整合有关Python字典的信息:

创建空词典

data = {}
# OR
data = dict()

使用初始值创建字典

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

插入/更新单个值

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)

插入/更新多个值

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Python 3.9+:

更新运算符|=现在适用于字典:

data |= {'c':3,'d':4}

创建合并词典而不修改原始词典

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Python 3.5+:

这使用了一个名为字典解包的新功能。

data = {**data1, **data2, **data3}

Python 3.9+:

合并运算符|现在适用于字典:

data = data1 | {'c':3,'d':4}

删除字典中的项目

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

检查字典中是否已存在密钥

key in data

遍历字典中的成对项

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

从两个列表创建词典

data = dict(zip(list_with_keys, list_with_values))

如果您不是在连接两个字典,而是在字典中添加新的键值对,那么使用下标表示法似乎是最好的方法。

import timeit

timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
>> 0.49582505226135254

timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
>> 0.20782899856567383

但是,如果您想添加数千个新的键值对,那么应该考虑使用update()方法。