簡體   English   中英

如何檢查 Python 字典是否具有特定鍵

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

因此,如果該術語尚未出現在該特定字典中,我想將該術語添加到字典中。 因此,如果Dict = {}並且我執行Dict.update({'hi':'hello'}) ,則 Dict 將以“ hi ”作為鍵。 現在說我有多個 Dict,例如DictDict1Dict2 ……等等。 現在我想這樣做,所以當我想將這個鍵:值對添加到 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM