我有一个工作问题,我需要能够从任意长的键列表中更新字典中的值。键列表和字典都是在运行时从相同的数据生成的,但我不知道之前的数据中有多少键。从数据中获取的键列表是用户在运行时指定的。
好的,所以这解决了必须能够从列表信息中更新字典中的值,该列表信息包括: 1. 键列表,按与字典中嵌套键相同的顺序排序 2. 要更新的值该键列表信息。
我有一个工作问题,我需要能够从任意长的键列表中更新字典中的值。键列表和字典都是在运行时从相同的数据生成的,但我不知道之前的数据中有多少键。从数据中获取的键列表是用户在运行时指定的。
好的,所以这解决了必须能够从列表信息中更新字典中的值,该列表信息包括: 1. 键列表,按与字典中嵌套键相同的顺序排序 2. 要更新的值该键列表信息。
我想我有一个解决方案,通过从这个站点清除: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}}