如何向现有词典中添加关键字?它没有.add()方法。
当前回答
这个问题已经得到了令人恶心的回答,但自从我议论获得了很大的牵引力,以下是答案:
添加新密钥而不更新现有字典
如果您在这里试图找出如何添加键并返回新字典(而不修改现有字典),可以使用以下技术来完成
Python>=3.5
new_dict = {**mydict, 'new_key': new_val}
Python<3.5
new_dict = dict(mydict, new_key=new_val)
注意,使用这种方法,您的密钥需要遵循Python中有效标识符名称的规则。
其他回答
如果您不是在连接两个字典,而是在字典中添加新的键值对,那么使用下标表示法似乎是最好的方法。
import timeit
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
>> 0.49582505226135254
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
>> 0.20782899856567383
但是,如果您想添加数千个新的键值对,那么应该考虑使用update()方法。
首先检查密钥是否已存在:
a={1:2,3:4}
a.get(1)
2
a.get(5)
None
然后可以添加新的键和值。
dico[“new key”]=“value”
我认为指出Python的集合模块也很有用,它由许多有用的字典子类和包装器组成,简化了字典中数据类型的添加和修改,特别是defaultdict:
调用工厂函数以提供缺失值的dict子类
如果您使用的字典总是由相同的数据类型或结构组成,例如列表字典,那么这尤其有用。
>>> from collections import defaultdict
>>> example = defaultdict(int)
>>> example['key'] += 1
>>> example['key']
defaultdict(<class 'int'>, {'key': 1})
如果键还不存在,defaultdict会将给定的值(在我们的例子中为10)作为初始值分配给字典(通常在循环中使用)。因此,此操作执行两件事:它向字典中添加一个新键(根据问题),如果键还不存在,则分配值。对于标准字典,当+=操作试图访问一个尚不存在的值时,这可能会引发错误:
>>> example = dict()
>>> example['key'] += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'key'
如果不使用defaultdict,添加新元素的代码量会更大,可能看起来像:
# This type of code would often be inside a loop
if 'key' not in example:
example['key'] = 0 # add key and initial value to dict; could also be a list
example['key'] += 1 # this is implementing a counter
defaultdict还可以用于复杂的数据类型,例如列表和集合:
>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})
添加元素会自动初始化列表。
您可以创建一个:
class myDict(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
## example
myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)
给予:
>>>
{'apples': 6, 'bananas': 3}
推荐文章
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字