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

前端 未结 5 610
执念已碎
执念已碎 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:38

    To insert a new key-value pair or update the value of a pair:

    import copy
    def update_nested_map(d, u, *keys):
        d = copy.deepcopy(d)
        keys = keys[0]
        if len(keys) > 1:
            d[keys[0]] = update_nested_map(d[keys[0]], u, keys[1:])
        else:
            d[keys[0]] = u
        return d
    

    test:

        >>> d = {'m': {'d': {'v': {'w': 1}}}}
    
        >>> update_nested_map(d, 999, ['m', 'd', 'v', 'w'])
        {'m': {'d': {'v': {'w': 999}}}}
    
        >>> update_nested_map(d, 999, ['m', 'd', 'v', 'z'])
        {'m': {'d': {'v': {'z': 999, 'w': 1}}}}
    
        >>> update_nested_map(d, 999, ['m', 'd', 'l'])
        {'m': {'d': {'v': {'w': 1}, 'l': 999}}}
    
        >>> update_nested_map(d, 999, ['m','d'])
        {'m': {'d': 999}}
    

提交回复
热议问题