
[英]Is there a Pythonic way to extend one dictionary with another (preserving all values)
[英]Is there a Pythonic way of adding float values of one dictionary to a list of values in another dictionary?
假设我有两个 Python 字典:
dictA = {20: [0.5, 1, 0.5], 25: [0.5, 1, 0.5]}
dictB = {20: 0.4, 25: 0.5}
第一个字典包含以浮点列表作为其值的键。 第二个包含具有浮点值的类似键。 我希望结果是 dictB 的浮点值与 dictA 列表中每个值的总和:
dictResult = {20: [0.9, 1.4, 0.9], 25: [1, 1.5, 1]}
我正在尝试以最简单的方式做到这一点,而无需使用许多代码行; (想让我的代码在未来更易于维护和阅读)。 这可以使用推导来完成吗?
使用字典理解
{ k: [x + dictB.get(k,0) for x in l] for k, l in dictA.items() }
Output
{20: [0.9, 1.4, 0.9], 25: [1.0, 1.5, 1.0]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.