【发布时间】:2022-01-10 03:51:08
【问题描述】:
我有一个类似的列表
myList= ['France', 'Brazil', 'Armenia']
还有一个像这样的字典:
countryDict = {'Argentina':10, 'Spain':23, 'France':66, 'Portugal:10', 'Brazil':120, 'Armenia':99}
如果字典中的键与列表匹配,我如何打印它的名称并用它打印值?
我试过这个:
for name in countries_avg_dict:
if name in country_List:
print(countries_avg_dict[name])
但是,这不起作用。有什么帮助吗?
我收到一个错误
DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use `array.size > 0` to check that an array is not empty.
【问题讨论】:
-
为什么不简单地遍历 list,从 dict 中获取该键的值,然后打印出来?
-
在解决了字典定义和名称不匹配的问题后,您的代码运行良好。请确保您的 minimal reproducible example 确实重现了您的问题
-
您显示的错误只能由 Numpy 数组引起,而不是内置
list。请确保您拥有reproducible example。 -
但是是的,迭代列表而不是字典会更干净。
标签: python list dictionary