为字典添加新键?

2024-04-24 15:51:18 发布

您现在位置:Python中文网/ 问答频道 /正文

在创建Python字典之后,是否可以将键添加到字典中?它似乎没有.add()方法。


Tags: 方法add字典将键
3条回答
d = {'key': 'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'key': 'value', 'mynewkey': 'mynewvalue'}

我想整合有关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'

在不修改原始词典的情况下创建合并词典

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

删除字典中的项目

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))

Python3的新成员

在不修改原始词典的情况下创建合并词典

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

请随意添加更多!

要同时添加多个键,请使用^{}

>>> 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}

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

相关问题 更多 >