如果不存在,Python将更新dict中的键 [英] Python update a key in dict if it doesn't exist
本文介绍了如果不存在,Python将更新dict中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果key不位于dict.keys()中,我想向dict中插入一个键-值对. 基本上我可以做到:
I want to insert a key-value pair into dict if key not in dict.keys(). Basically I could do it with:
if key not in d.keys():
d[key] = value
但是有更好的方法吗?还是该问题的pythonic解决方案是什么?
But is there a better way? Or what's the pythonic solution to this problem?
推荐答案
您不需要致电d.keys()
,所以
if key not in d:
d[key] = value
就足够了.没有更清晰,更易读的方法.
is enough. There is no clearer, more readable method.
您可以再次使用dict.get()
更新,如果键已经存在,它将返回一个现有值:
You could update again with dict.get()
, which would return an existing value if the key is already present:
d[key] = d.get(key, value)
但我强烈建议您反对;这是代码打高尔夫球,妨碍了维护和可读性.
but I strongly recommend against this; this is code golfing, hindering maintenance and readability.
这篇关于如果不存在,Python将更新dict中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文