Setting a value in a nested python dictionary given a list of indices and value

后端 未结 8 878
忘了有多久
忘了有多久 2020-12-01 09:36

I\'m trying to programmatically set a value in a dictionary, potentially nested, given a list of indices and a value.

So for example, let\'s say my list of indices i

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 10:01

    Use these pair of methods

    def gattr(d, *attrs):
        """
        This method receives a dict and list of attributes to return the innermost value of the give dict
        """
        try:
            for at in attrs:
                d = d[at]
            return d
        except:
            return None
    
    
    def sattr(d, *attrs):
        """
        Adds "val" to dict in the hierarchy mentioned via *attrs
        For ex:
        sattr(animals, "cat", "leg","fingers", 4) is equivalent to animals["cat"]["leg"]["fingers"]=4
        This method creates necessary objects until it reaches the final depth
        This behaviour is also known as autovivification and plenty of implementation are around
        This implementation addresses the corner case of replacing existing primitives
        https://gist.github.com/hrldcpr/2012250#gistcomment-1779319
        """
        for attr in attrs[:-2]:
            # If such key is not found or the value is primitive supply an empty dict
            if d.get(attr) is None or isinstance(d.get(attr), dict):
                d[attr] = {}
            d = d[attr]
        d[attrs[-2]] = attrs[-1]
    

提交回复
热议问题