How to set dictionary element with key as array?

Viewed 48

If I wanted to use an array to get a value from a dictionary, I would do something like this:

def get_dict_with_arr(d, arr):
    accumulator = d
    for elem in arr:
        accumulator = accumulator[elem]
    return accumulator

and use it like this:

test_dict = {
  'this': {
    'is': {
      'it': 'test'
    }
  }
}

get_dict_with_arr(test_dict, ['this', 'is', 'it']) # returns 'test'

My question is, how may I write a function that sets the value instead of getting it? Basically I want to write a set_dict_with_arr(d, arr, value) function.

1 Answers

Try:

def set_dict_with_arr(d, arr, value):
    cur_d = d
    for v in arr[:-1]:
        cur_d.setdefault(v, {})
        cur_d = cur_d[v]
    cur_d[arr[-1]] = value
    return d


test_dict = {"this": {"is": {"it": "test"}}}


test_dict = set_dict_with_arr(test_dict, ["this", "is", "it"], "new value")
print(test_dict)

Prints:

{"this": {"is": {"it": "new value"}}}
Related