如何向字典添加新键?
我怎么往一个已经存在的字典里添加一个新键呢?字典没有.add()
这个方法。
21 个回答
1232
要同时添加多个键,可以使用 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}
如果只添加一个键,接受的答案在计算上会更简单一些。
1314
我觉得有必要把关于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))
4389
你可以通过给一个键(key)赋值来在字典(dictionary)中创建一个新的键值对(key/value pair)。
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
如果这个键之前不存在,就会被添加进字典,并指向你赋的这个值。如果这个键已经存在,那么它原来指向的值就会被新的值覆盖掉。