小编典典

是否可以在创建 Python 字典后为其添加键?

python

是否可以在创建 Python 字典后为其添加键?

好像没有.add()方法。


阅读 313

收藏
2022-01-18

共3个答案

小编典典

您通过为该键分配一个值来在字典上创建一个新的键/值对

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

d['mynewkey'] = 'mynewvalue'

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

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

2022-01-18
小编典典

要同时添加多个键,请使用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}

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

2022-01-18
小编典典

我想整合有关 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))
2022-01-18