Search code examples
pythonpython-3.xdictionarydefaultdict

KeyError while populating a dictionary of dictionaries


I essentially need a dictionary of dictionaries in the following format:

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

This code is what I have so far:

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"]

However, I want to be able to simplify/generalise it in this manner as the above code is long and non-Pythonic:

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

But it raises a KeyError. How do I overcome this?

Cheers!


Solution

  • In order to populate cable_footage dynamically, it should be defined as nested defaultdict (defaultdict of defaultdicts).

    Try this out:

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

    Then, inside you nested loop just populate it:

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