繁体   English   中英

如何比较具有相同键的两个字典并使用 python 中的条件更新值?

[英]How to compare two dictionaries with the same keys and update values with a condition in python?

d1 = {'a': 5, 'b': 8, 'c': 5}
d2 = {'a': 9, 'b': 4, 'c': 7}

如果 d2 中的值小于 d1 中的值,我想更新 d1 中的值以获取新字典 d:

d = {'a': 5, 'b': 4, 'c': 5}

你可以这样做:

d1 = {'a': 5, 'b': 8, 'c': 5}
d2 = {'a': 9, 'b': 4, 'c': 7}

>>> dict([min(i, j) for i, j in zip(d1.items(), d2.items())])
{'a': 5, 'b': 4, 'c': 5}

zip(d1.items(), d2.items())加入两个dict中的项目,然后迭代这些项目和 select 两者的min ,再次用dict制作字典。

d1 = {'a': 5, 'b': 8, 'c': 5}
d2 = {'a': 9, 'b': 4, 'c': 7}

d = {k:min(v,d2[k]) for k,v in d1.items()}

print(d)
# {'a': 5, 'b': 4, 'c': 5}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM