Change values in dict of nested dicts using items in a list?

前端 未结 5 608
执念已碎
执念已碎 2020-11-29 10:09

How would you modify/create keys/values in a dict of nested dicts based on the values of a list, in which the last item of the list is a value for the dict, and the rest of

5条回答
  •  悲&欢浪女
    2020-11-29 10:35

    address_list = ["key1", "key1.1", "key1.2", "value"]
    
    def set_value(dict_nested, address_list):
        cur = dict_nested
        for path_item in address_list[:-2]:
            try:
                cur = cur[path_item]
            except KeyError:
                cur = cur[path_item] = {}
        cur[address_list[-2]] = address_list[-1]
    

提交回复
热议问题