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


当前回答

首先检查密钥是否已存在:

a={1:2,3:4}
a.get(1)
2
a.get(5)
None

然后可以添加新的键和值。

其他回答

如果您想在字典中添加字典,可以这样做。

示例:向字典和子字典添加新条目

dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)

输出:

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}

注意:Python要求您首先添加子

dictionary["dictionary_within_a_dictionary"] = {}

在添加条目之前。

dictionary[key] = value

常规语法是d[key]=value,但如果您的键盘缺少方括号键,您也可以这样做:

d.__setitem__(key, value)

事实上,定义__getitem__和__setitem__方法是如何使自己的类支持方括号语法的。请参见深入Python,类似字典的类。

我认为指出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]})

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

通过为字典中的键指定值,可以在字典中创建新的键/值对

d = {'key': 'value'}
print(d)  # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}

如果键不存在,则添加该键并指向该值。如果它存在,它所指向的当前值将被覆盖。