简体   繁体   中英

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. Now say that I have multiple Dicts, such as Dict , Dict1 , Dict2 ... and so on. 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.

Right now I am stuck on using if [key] in Dict , then like add it to another, but that doesn't seem to work.

You can put your dicts inside a list then check if the key in the first dict to move the next one, for example:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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