如何向现有字典添加键?它没有 .add()
方法。
原文由 lfaraone 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想整合有关 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))
原文由 Yugal Jindle 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答874 阅读✓ 已解决
1 回答1.8k 阅读✓ 已解决
您通过为该键分配一个值来在字典上创建一个新的键/值对
如果键不存在,则添加它并指向该值。如果存在,则覆盖它指向的当前值。