使用任意长的值列表更新python字典

时间:2015-10-07 04:52:46

标签: list python-2.7 nested autovivification

我有一个工作问题,我需要能够从任意长的键列表中更新字典中的值。密钥列表和字典都是在运行时从相同的数据生成的,但我不知道之前数据中有多少个密钥。从数据中获取的密钥列表是在运行时用户指定的。

好的,所以这必须能够从包含以下内容的列表信息更新字典中的值: 1.一个键列表,按照与字典中的键嵌套相同的顺序排序 2.根据该密钥列表信息更新的值。

1 个答案:

答案 0 :(得分:0)

我想我已经有了一个解决方案,通过从这个站点清除:https://gist.github.com/hrldcpr/2012250,以及python autoviv(),我比这个默认树对象更喜欢。

这是我的解决方案。根据您为函数提供的内容,您应该能够从列表生成字典,和/或更新结构中特定位置的值。

如果您发现明显的错误或改进机会,我将非常感谢您的建设性反馈。

from pprint import *
from collections import defaultdict
from operator import getitem

class autoviv(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

def add(t,path,genorupdate='generate',val=0):
    if genorupdate=='generate':
        for node in path:
            t = t[node]         
    elif genorupdate=='update':
        for node in path:
            if path.index(node)==len(path)-1:
                t[node]=val     
            t = t[node] 

d=autoviv()

# test lists to generate dictionary

l=['a','b','c']
l2=['a','b','d']

# TEST 1: generate dictionary with 2 kvps: c and d, nested under b:

add(d,l)
add(d,l2)

for k in d.keys():
    print k, d[k]

# RESULT: a {'b': {'c': {}, 'd': {}}}

# TEST 2, update the value for the a,b,d key to 2 w/o disturbing anything else or
    # generating additional structure

add(d,l2,'update',2)

for k in d.keys():
    print k, d[k]

# RESULT: a {'b': {'c': {}, 'd': 2}}