簡體   English   中英

遍歷列表並與嵌套字典進行比較。 避免 KeyError - Python

[英]Loop through list and compare against nested dict. avoiding KeyError - Python

我想做以下事情:

到目前為止,我得到了以下代碼,但我現在被困在如何從循環中執行的未來操作中忽略那一天。

如果有人可以幫助我,那將非常感激!

  • 請注意,我不能將 EU 作為一個區域刪除,即使密鑰不在嵌套字典中,也需要將其納入邏輯。

錯誤與您有關

print("{} status is: ".format(region) + nested_status)

nested_status 是 NullType,但 print 語句需要一個字符串。

你可以嘗試這樣的事情來避免'NonTypes'

dict.get(key[, default])
example
dict.get(key, -1)

檢查此代碼段並相應地修改您的代碼

print(nested)
nested['SA'].pop('20200525')
print(nested)

這是一個可行的解決方案,請檢查底部的更新答案。

您收到“無法連接”錯誤的原因是因為“nested_status”在某些迭代中等於“None”,並且您嘗試在 print 語句中添加一個字符串('...' + None)。 您應該首先檢查nested_status 是否有值。

import datetime

dates = [datetime.datetime(2020, 7, 4, 0, 0), datetime.datetime(
    2020, 7, 6, 0, 0), datetime.datetime(2020, 7, 7, 0, 0)]

regions = ["SA", "CA", "EU"]

nested = {"SA": {"20200525": "H", "20201126": "C", "20201224": "H", "20200101": "C", "20201127": "C", "20200217": "C", "20200120": "C", "20200907": "C", "20200410": "C", "20200704": "C",
                 "20201225": "C"}, "CA": {"20200410": "C", "20200518": "C", "20200701": "C", "20200101": "C", "20201012": "C", "20201228": "C", "20201225": "C", "20200803": "C", "20200907": "C", "20200217": "C"}}

for region in regions:
    for d in dates:
        day = d.strftime("%Y%m%d")

        if (nested.get(region) or {}).get(day):
            print("Nested value found in {} ! {}".format(region, day))
        nested_status = (nested.get(region) or {}).get(day)
        if nested_status:
            if nested_status == 'C':
                continue                 #<-- skip this loop iteration if C
            print("{} status is: ".format(region) + nested_status)

如果您對“如果nested_status == C”不感興趣,請跳過當前日期迭代。

if nested_status:
    if nested_status == 'C':
        continue                 #<-- skip this loop iteration if C
    print("{} status is: ".format(region) + nested_status)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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