填充字典字典时出现 KeyError

KeyError while populating a dictionary of dictionaries

我基本上需要以下格式的字典:

cable_footage = {"AER": {144: len1, 48: len2, 24: len3}, "UG": {144: len1, 48: len2, 24: len3}}

这段代码是我目前所拥有的:

cable_footage = defaultdict(dict)
    for placement in ("AER", "UG"):
        for size in (144, 48, 24):
            cable_footage[placement][size] = 0.0
    for cable in adss_layer.features:
        if cable.data["Placement"] == "AER":
            if cable.data["Size"] == 144:
                cable_footage["AER"][144] += cable.data["Length"]
            if cable.data["Size"] == 48:
                cable_footage["AER"][48] += cable.data["Length"]
        if cable.data["Placement"] == "UG":
            if cable.data["Size"] == 144:
                cable_footage["UG"][144] += cable.data["Length"]
            if cable.data["Size"] == 48:
                cable_footage["UG"][48] += cable.data["Length"]

但是,我希望能够以这种方式 simplify/generalise 它,因为上面的代码很长而且不是 Pythonic:

for cable in adss_layer.features:
    cable_footage[cable.data["Placement"]][cable.data["Size"]] += cable.data["Length"]

但它引发了 KeyError。我该如何克服这个问题?

干杯!

为了动态填充 cable_footage,应将其定义为嵌套 defaultdictdefaultdict 个,共 defaultdict 个)。

试试这个:

cable_footage = defaultdict(lambda: defaultdict(float)))

然后,在嵌套循环中填充它:

cable_footage[cable.data["Placement"]][cable.data["Size"]] += cable.data["Length"]