繁体   English   中英

比较一个字典中的值与Python中另一个字典中的值

[英]Comparing values in one dictionary with values from another dictionary in Python

我有两个字典:

dict1 = {'Canada' : 2.5, 'UK' : 3.7, 'USA' : 9.0}
dict2 = {'a' : 7, 'b' : 2}

我希望能够遍历中的 dict1使用中的值dict2以确定哪些元素是较大的。 输出应为:

a is larger than Canada.
a is larger than UK.

(因为7明显大于2.5和3.7)。 我希望这是有道理的!

到目前为止,我已经写了:

for k, v in dict2.items():
    for i, j in dict2:
        print (k, " is larger than ", i)

我收到此错误: ValueError: too many values to unpack (expected 2)

任何帮助,将不胜感激!

您有正确的主意。 迭代两个字典中的项目并进行比较

>>> dict1 = {'Canada' : 2.5, 'UK' : 3.7, 'USA' : 9.0}
>>> dict2 = {'a' : 7, 'b' : 2}
>>> 
>>> 
>>> for kd2, vd2 in dict2.items():
...     for kd1, vd1 in dict1.items():
...         if vd2 > vd1:
...             print(kd2, "is larger than", kd1)
... 
a is larger than Canada
a is larger than UK

你所得到的错误仅仅是由于您缺少的.items()在遍历dict2 您只是在遍历键,所以它不知道如何处理i, j

暂无
暂无

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

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