-3

I have an odd question. If I were to have a dictionary like so:

{"foo":{"abc":123},"bar":{"def":456},"biz":789}

and I had a list of indexes like so:

["foo","abc"]

How would I GET AND MODIFY that item? I've seen questions like it, but all the answers tell me to make a bunch of indexes ex:

foobar["foo"]["abc"] = "modified"

But the problem is that my indexes are in lists. Also, I could do something like ["foo","abc","more","items"] and that would need to equate to foobar["foo"]["abc"]["more"]["items"]

Is there some way that I could get and modify an item in a dictionary using a list of indexes?

xcrafter_40
  • 107
  • 1
  • 10

1 Answers1

1

That is fairly straight forward using recursion like:

Code:

def dict_access_multi(a_dict, keys):
    if len(keys) == 0:
        return a_dict
    return dict_access_multi(a_dict[keys[0]], keys[1:])

Test Code:

data = {"foo": {"abc": 123}, "bar": {"def": 456}, "biz": 789}

print(dict_access_multi(data, ["foo", "abc"]))
print(dict_access_multi(data, ["bar", "def"]))
print(dict_access_multi(data, ["biz"]))

Results:

123
456
789
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135