[英]Find if a value in a list exists in a dictionary in python
I have a list which is like我有一个清单,就像
myList= ['France', 'Brazil', 'Armenia']
and a dictionary which is like和一本像
countryDict = {'Argentina':10, 'Spain':23, 'France':66, 'Portugal:10', 'Brazil':120, 'Armenia':99}
How do i print the names of the key in the dictionary if it matches the list, and print the value with it?如果它与列表匹配,我如何打印字典中键的名称,并用它打印值?
I tried我试过了
for name in countries_avg_dict:
if name in country_List:
print(countries_avg_dict[name])
However This doesn't work, any help?但是这不起作用,有什么帮助吗?
Im getting an error which is我收到一个错误
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.
You need to iterate over the myList
and check if a country in it is in countryDict
:您需要遍历
myList
并检查其中的国家/地区是否在countryDict
中:
for country in myList:
if country in countryDict:
print(country, countryDict[country])
Output: Output:
France 66
Brazil 120
Armenia 99
You don't need to do a nested loop to find if they are in the dictionary, simply use the bool()
operator in order to find if the element exist, you can do this inside a try-except to catch the KeyError in case the element doesn't exists in the dictionary您不需要执行嵌套循环来查找它们是否在字典中,只需使用
bool()
运算符来查找元素是否存在,您可以在 try-except 中执行此操作以捕获 KeyError 以防万一该元素在字典中不存在
using for each loop:使用每个循环:
myList= ['France', 'Brazil', 'Armenia', 'FakeCountry']
countryDict = {'Argentina':10, 'Spain':23, 'France':66, 'Portugal':10, 'Brazil':120, 'Armenia':99}
for item in myList:
try:
print(item, bool(countryDict[item]))
except KeyError:
print(item, False)
Using indexed for:使用索引:
myList= ['France', 'Brazil', 'Armenia', 'FakeCountry']
countryDict = {'Argentina':10, 'Spain':23, 'France':66, 'Portugal':10, 'Brazil':120, 'Armenia':99}
for i in range(len(myList)):
try:
print(myList[i], bool(countryDict[myList[i]]))
except KeyError:
print(myList[i], False)
I believe this may be helpful:我相信这可能会有所帮助:
>>> for k,v in countryDict.items():
... if k in myList:
... print(f"{k}: {v}")
...
France: 66
Brazil: 120
Armenia: 99
Please let me know if this works for you.请让我知道这是否适合您。 ~X
~X
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.