【问题标题】:How to set dictionary element with key as array?如何将带有键的字典元素设置为数组?
【发布时间】:2021-09-21 03:08:15
【问题描述】:

如果我想使用数组从字典中获取值,我会这样做:

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

并像这样使用它:

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

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

我的问题是,我如何编写一个设置值而不是获取值的函数?基本上我想写一个set_dict_with_arr(d, arr, value)函数。

【问题讨论】:

    标签: python arrays dictionary key


    【解决方案1】:

    试试:

    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)
    

    打印:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 2016-12-27
      • 2020-05-02
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多