Python如果不存在则更新dict中的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42315072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python update a key in dict if it doesn't exist
提问by Xiaochen Cui
I want to insert a key-value pair into dict if key not in dict.keys(). Basically I could do it with:
如果键不在 dict.keys() 中,我想在 dict 中插入一个键值对。基本上我可以做到:
if key not in d.keys():
d[key] = value
But is there a better way? Or what's the pythonic solution to this problem?
但是有更好的方法吗?或者这个问题的pythonic解决方案是什么?
回答by Martijn Pieters
You do not need to call d.keys()
, so
你不需要打电话d.keys()
,所以
if key not in d:
d[key] = value
is enough. There is no clearer, more readable method.
足够。没有更清晰、更易读的方法。
You could update again with dict.get()
, which would return an existing value if the key is already present:
您可以使用 再次更新dict.get()
,如果键已经存在,它将返回一个现有值:
d[key] = d.get(key, value)
but I strongly recommend against this; this is code golfing, hindering maintenance and readability.
但我强烈建议不要这样做;这是代码打高尔夫球,阻碍了维护和可读性。
回答by mhawke
Use dict.setdefault()
:
>>> d = {1: 'one'}
>>> d.setdefault(1, '1')
'one'
>>> d # d has not changed because the key already existed
{1: 'one'}
>>> d.setdefault(2, 'two')
'two'
>>> d
{1: 'one', 2: 'two'}
回答by Rotareti
Since Python 3.9you can use the merge operator|
to merge two dictionaries. The dict on the right takes precedence:
从Python 3.9 开始,您可以使用合并运算符|
来合并两个字典。右边的 dict 优先:
d = { key: value } | d
Note: this creates a new dictionary with the updated values.
注意:这会使用更新的值创建一个新字典。
回答by CoderKid
With the following you can insert multiple values and also have default values but you're creating a new dictionary.
使用以下内容,您可以插入多个值并具有默认值,但您正在创建一个新字典。
d = {**{ key: value }, **default_values}
I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .
我已经用投票最多的答案对其进行了测试,平均而言,速度更快,如下例所示。
Speed test comparing a for loop based method with a dict comprehension with unpack operator method.
速度测试将基于 for 循环的方法与具有解包运算符方法的 dict 理解进行比较。
if no copy (d = default_vals.copy()
) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5
and greater. Memory footprint of both methods are the same.
如果d = default_vals.copy()
在第一个案例中没有复制 ( ) ,那么一旦我们达到10**5
和更大的数量级,投票最多的答案就会更快。两种方法的内存占用是相同的。