网友问题:
如何向现有词典添加键?它没有方法。.add()
网友回答:
我想整合有关 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'
更新运算符现在适用于字典:|=
data |= {'c':3,'d':4}
data3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
这使用了一项称为字典解包的新功能。
data = {**data1, **data2, **data3}
合并运算符现在适用于字典:|
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))
网友回答:
通过在字典上为该键赋值来创建新的键/值对
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向现有词典添加键?它没有方法。.add()】,大小是暂无信息,文档格式为.html,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。