假设当用户提供的表达式为true并且允许表达式引用任一dict字段时,我想组合两个dicts。这是一个例子:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'m': 1, 'n': 3, 'o': 5}
dict3 = {'m': 2, 'n': 4, 'o': 6}
expression = "target['a'] == source['m']
期望的结果:
new_dict = {'a': 1, 'b': 2, 'c': 3, 'sub_dict': {'m': 1, 'n': 3, 'o': 5}}
我想出的最佳解决方案是:
def combine(source, target, expression):
try:
if eval(expression):
target['sub_dict'] = source
except:
pass
如果没有为条件表达式编写DSL,是否有更好的替代方法,允许在没有预先知道源的结构和内容的目标(单独的模块)的情况下合并字典,反之亦然?
答案 0 :(得分:1)
如果您只需要比较词典之间的指定值,则应该能够通过在每个eval
中指定键而不是完整表达式来避免dict
。
def combine(source, target, source_key, target_key):
try:
if source[source_key] == target[target_key]:
target['sub_dict'] = source
except KeyError:
# do something here?
pass