简体   繁体   English

如何检查 Python 字典是否具有特定键

[英]How to check if a Python dict has a specific key

So I want to add the term to the Dict if the term is not yet present in that particular Dict.因此,如果该术语尚未出现在该特定字典中,我想将该术语添加到字典中。 So if Dict = {} , and I do Dict.update({'hi':'hello'}) , the Dict would have the ' hi ' as the key.因此,如果Dict = {}并且我执行Dict.update({'hi':'hello'}) ,则 Dict 将以“ hi ”作为键。 Now say that I have multiple Dicts, such as Dict , Dict1 , Dict2 ... and so on.现在说我有多个 Dict,例如DictDict1Dict2 ……等等。 And now I want to make it so when I want to add this key:value pair into the Dict, if Dict has it, then it will go automatically to Dict1 , and if Dict1 has it, then to Dict2 and so on.现在我想这样做,所以当我想将这个键:值对添加到 Dict 中时,如果 Dict 有它,那么它将 go 自动到Dict1 ,如果Dict1有它,那么到Dict2等等。

Right now I am stuck on using if [key] in Dict , then like add it to another, but that doesn't seem to work.现在我坚持if [key] in Dict ,然后将其添加到另一个中,但这似乎不起作用。

You can put your dicts inside a list then check if the key in the first dict to move the next one, for example:您可以将您的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM