[英]What's the best way to map a dict value to another dict
我想知道将2个dict1 = {k1: v1, k2: v2, ...}
合并为一个dict的最佳方法是: dict1 = {k1: v1, k2: v2, ...}
和dict2 = {v1: w1, v2: w2, ...}
into result = {k1: w1, k2: w2, ...}
我已经有了使用dict理解的解决方案:
result = {
k: dict2[v]
for k, v in dict1.items()
}
但我不认为这是最优雅的方式。 你能帮我么 ?
对于双字典案例,你的字典理解很好。 这是假设你能保证你的价值观dict1
是关键dict2
。
考虑如何将其扩展到任意字典输入,您可以使用for
循环:
dict1 = {'k1': 'v1', 'k2': 'v2'}
dict2 = {'v1': 'w1', 'v2': 'w2'}
dict3 = {'w1': 'x1', 'w2': 'x2'}
def chainer(first, *others):
res = first.copy() # make a copy to avoid overwriting dict1
for k, v in res.items():
for dct in others:
v = dct[v]
res[k] = v
return res
res = chainer(dict1, dict2, dict3)
# {'k1': 'x1', 'k2': 'x2'}
作为替代/扩展,对于@jpp的答案 ,您还可以使用reduce
/ functools.reduce
来获得稍微更精简的chainer
函数形式:
from functools import reduce
def chainer(first, *others):
return {k: reduce(lambda x, d: d[x], others, v) for k, v in first.items()}
其中哪一个更好主要是品味问题; 用法和结果是一样的。
对于只有两本词典,你的字典理解是恕我直言,它是优雅和优雅的。 但是,如果第二个字典中没有键,则可能需要使用get
或添加条件。
>>> dict1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
>>> dict2 = {'v1': 'w1', 'v2': 'w2'}
>>> {k: dict2.get(v, 'undefined') for k, v in dict1.items()}
{'k1': 'w1', 'k2': 'w2', 'k3': 'undefined'}
>>> {k: dict2[v] for k, v in dict1.items() if v in dict2}
{'k1': 'w1', 'k2': 'w2'}
将这样的保护措施添加到chainer
会涉及更多,特别是对于使用reduce
这种变体(可能根本不需要)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.