[英]How to check if a Python dict has a specific key
因此,如果该术语尚未出现在该特定字典中,我想将该术语添加到字典中。 因此,如果Dict = {}
并且我执行Dict.update({'hi':'hello'})
,则 Dict 将以“ hi
”作为键。 现在说我有多个 Dict,例如Dict
、 Dict1
、 Dict2
……等等。 现在我想这样做,所以当我想将这个键:值对添加到 Dict 中时,如果 Dict 有它,那么它将 go 自动到Dict1
,如果Dict1
有它,那么到Dict2
等等。
现在我坚持if [key] in Dict
,然后将其添加到另一个中,但这似乎不起作用。
您可以将您的 dicts 放在一个列表中,然后检查第一个 dict 中的键是否移动下一个,例如:
# some dicts
dict1 = {'cats': 1, 'dogs': 2, 'fish': 3}
dict2 = {'cow': 4}
dict3 = {}
# add the dicts inside a list
dicts = [dict1, dict2 dict3]
# assume I want to add {'dogs': 2} to my dicts
key = 'dogs'
value = 2
# iterate overall dicts inorder to find a dict doesn't contain the key
for dict in dicts:
# this will skip all dicts that contains the key
# so it automatically will go to the next dict
if key not in dict:
dict.update({key: value})
# stop updating after finding the next dict
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.