我有一组属于用户的值,它们将成为给定函数的参数。我将比较多个组,每个组都有自己的假设 - 大约80%的时间它们是公共变量(尽管不是值本身)。
我将比新用户更频繁地添加新变量,因此我宁愿将数据捆绑为每个变量的字典。
如何最好地遍历假设数据以编译给定用户的字典?
换句话说,从这里开始:
assumptions.py
var_x = {'user_1': 10, 'user_2': 15, 'user_3': 12}
var_y = {'user_1': 1000, 'user_3': 950} # nothing for user_2
var_z = {'user_1': 3, 'user_2': 2, 'user_3': 3}
到这里:
foobar.py
user = 'user_2'
<transpose>
user_dict = {'var_x':15, 'var_y':None, 'var_z':2}
任何建议都将不胜感激。感谢。
答案 0 :(得分:1)
我认为来自collections
模块的defaultdict
正是您要找的。 p>
这是一个例子
from collections import defaultdict
# you must use `lambda` here as using just `None` will result with
# KeyError on undefined keys
fund_dict = defaultdict(lambda: None, {'assume01':15, 'assume03':2})
print fund_def['assume01'] # outputs 15
print fund_def['assume02'] # outputs None
print fund_def['assume03'] # outputs 2
答案 1 :(得分:1)
这是一种将多个词典链接在一起的方法(一个具有默认值,另一个具有更新的假设):
import UserDict
class Chainmap(UserDict.DictMixin):
"""Combine multiple mappings for successive lookups.
For example, to emulate Python's normal lookup sequence:
import __builtin__
pylookup = Chainmap(locals(), globals(), vars(__builtin__))
"""
def __init__(self, *maps):
self._maps = maps
def __getitem__(self, key):
for mapping in self._maps:
try:
return mapping[key]
except KeyError:
pass
raise KeyError(key)
def keys(self):
result = []
seen = set()
for mapping in self_maps:
for key in mapping:
if key not in seen:
result.append(key)
seen.add(key)
return result
有关更完整的字典界面,请参阅init.py#l754“&gt; http://hg.python.org/cpython/file/ab5d39caad6f/Lib/collections/ init .py# L754
ChainMap 类可以像这样使用:
base_assumptions = dict(a1=10, a2=15, a3=30)
class FundClass:
def __init__(self, fund, investor_assumptions) #dict to be unpacked via '**' when passed
combined_dict = ChainMap(investor_assumptions, base_assumptions)
self.some_var = combined_dict['a1']
答案 2 :(得分:0)
assumptions = {'assume01': {'fund1':10, 'fund2':15, 'fund3':12},
'assume02': {'fund1':1000, 'fund3':950},
'assume03': {'fund1':3, 'fund2':2, 'fund3':3}}
def fund_assumptions(fund):
return dict((k, assumptions[k].get(fund)) for k in assumptions)
print fund_assumptions('fund2')
#prints {'assume02': None, 'assume03': 2, 'assume01': 15}
答案 3 :(得分:0)
假设假设与脚本位于同一目录中
import assumptions
fund = "..."
fund_dict = {}
for d in dir(assumptions):
element = eval("assumptions." + d)
if isinstance(element, dict) and d[6:] == "assume": # in case there are other dictionaries in the file
if fund in element:
fund_dict[d] = element[fund]
else:
fund_dict[d] = None
# using your example:
# print fund_dict prints {'assume01': 15, 'assume02': None, 'assume03': 2}