如何向现有词典中添加关键字?它没有.add()方法。
当前回答
在不使用add的情况下向字典中添加关键字
# Inserting/Updating single value
# subscript notation method
d['mynewkey'] = 'mynewvalue' # Updates if 'a' exists, else adds 'a'
# OR
d.update({'mynewkey': 'mynewvalue'})
# OR
d.update(dict('mynewkey'='mynewvalue'))
# OR
d.update('mynewkey'='mynewvalue')
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
# To add/update multiple keys simultaneously, use d.update():
x = {3:4, 5:6, 7:8}
d.update(x)
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue', 3: 4, 5: 6, 7: 8}
# update operator |= now works for dictionaries:
d |= {'c':3,'d':4}
# Assigning new key value pair using dictionary unpacking.
data1 = {4:6, 9:10, 17:20}
data2 = {20:30, 32:48, 90:100}
data3 = { 38:"value", 99:"notvalid"}
d = {**data1, **data2, **data3}
# The merge operator | now works for dictionaries:
data = data1 | {'c':3,'d':4}
# Create a dictionary from two lists
data = dict(zip(list_with_keys, list_with_values))
其他回答
这个流行的问题涉及合并字典a和b的函数方法。
下面是一些更简单的方法(在Python 3中测试过)。。。
c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )
注意:上面的第一个方法仅在b中的键是字符串时有效。
要添加或修改单个元素,b字典将仅包含该元素。。。
c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'
这相当于。。。
def functional_dict_add( dictionary, key, value ):
temp = dictionary.copy()
temp[key] = value
return temp
c = functional_dict_add( a, 'd', 'dog' )
dictionary[key] = value
通过为字典中的键指定值,可以在字典中创建新的键/值对
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
如果键不存在,则添加该键并指向该值。如果它存在,它所指向的当前值将被覆盖。
要同时添加多个键,请使用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}
对于添加单个密钥,接受的答案具有较少的计算开销。
我想整合有关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))
推荐文章
- 输入对象的datetime。Datetime没有Datetime属性
- numpy数组的Python内存使用情况
- NumPy或Pandas:保持数组类型为整数,同时具有NaN值
- 列表理解条件中的' elif '
- Python的“property”和“attribute”有什么区别?
- 在Python中格式化多行字典的正确方法是什么?
- 向异常添加信息?
- Sphinx autodoc不够自动
- 如何限制Django模型中数值字段的最大值?
- 访问对象内存地址
- 为什么在Python方法中需要显式地有“self”参数?
- 如何升级Windows 10下的Python安装?
- tqdm在Jupyter笔记本重复打印新的进度条
- 如何在for循环中注释类型?
- 如何替换一个Pandas数据框架的字符串列中的文本?