填充字典时出现 KeyError

Anu*_*esh 1 python dictionary python-3.x defaultdict

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

cable_footage = {"AER": {144: len1, 48: len2, 24: len3}, "UG": {144: len1, 48: len2, 24: len3}}
Run Code Online (Sandbox Code Playgroud)

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

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"]
Run Code Online (Sandbox Code Playgroud)

但是,我希望能够以这种方式简化/概括它,因为上面的代码很长且非 Pythonic:

for cable in adss_layer.features:
    cable_footage[cable.data["Placement"]][cable.data["Size"]] += cable.data["Length"]
Run Code Online (Sandbox Code Playgroud)

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

干杯!

Gab*_*bip 5

为了cable_footage动态填充,它应该被定义为nested defaultdict( defaultdictof defaultdicts)。

试试这个:

cable_footage = defaultdict(lambda: defaultdict(float)))
Run Code Online (Sandbox Code Playgroud)

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

cable_footage[cable.data["Placement"]][cable.data["Size"]] += cable.data["Length"]
Run Code Online (Sandbox Code Playgroud)