简体   繁体   English

遍历列表并与嵌套字典进行比较。 避免 KeyError - Python

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

I would like to do the following:我想做以下事情:

I got to the following code so far, but I'm stuck now how to ignore that Day from future actions performed in the loop.到目前为止,我得到了以下代码,但我现在被困在如何从循环中执行的未来操作中忽略那一天。

If someone could help me that would be really appreciated!!如果有人可以帮助我,那将非常感激!

  • Note that I cannot remove EU as a region, it needs to be taken into the logic even though the key is not in the nested dict.请注意,我不能将 EU 作为一个区域删除,即使密钥不在嵌套字典中,也需要将其纳入逻辑。

error has to do with your错误与您有关

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

nested_status is NullType, but the print statement is expecting a string. nested_status 是 NullType,但 print 语句需要一个字符串。

You could try something like this to avoid 'NonTypes'你可以尝试这样的事情来避免'NonTypes'

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

check this snippet and modify your code accordingly检查此代码段并相应地修改您的代码

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

Here is a working solution, check the updated answer at the bottom.这是一个可行的解决方案,请检查底部的更新答案。

The reason you getting the "can not concatenate" Error is because "nested_status" is equal to "None" in some iterations and you tried to add a string to it ('...' + None) in the print statement.您收到“无法连接”错误的原因是因为“nested_status”在某些迭代中等于“None”,并且您尝试在 print 语句中添加一个字符串('...' + None)。 you should check if nested_status has a value first.您应该首先检查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)

if you are not interested "if nested_status == C" just skip the current date iteration.如果您对“如果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