Search code examples
pythondictionaryoverridinggetter-setter

Python get/set value of dict of dicts by key in variable


I have dict of dicts in Python, it can be deep, not just 2 levels.

data = {
    0: {
        1: {
            2: "Yes"
        },
        3: {
            4: "No"
        }
    },
}

I need to get and set the data, but the key is dynamic and is stored in list

key_to_get = [0,1,2]

print(data.get(key_to_get))

Should print Yes

Ideas?


Solution

  • Here is a simple recursive function which solves the problem

    def getValue(dict, keys):
        if len(keys) == 1:
            return dict.get(keys[0])
        return getValue(dict.get(keys[0]), keys[1:])
    

    And an iterative approach if you're boring

    temp = data
    for key in key_to_get:
        temp = temp.get(key)
    print(temp)