'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 that is like this:
countryDict = {'Argentina':10, 'Spain':23, 'France':66,
'Portugal:10', 'Brazil':120, 'Armenia':99}
How can I print the names of the key in the dictionary if it matches the list and print the value with it?
I tried this:
for name in countries_avg_dict:
if name in country_List:
print(countries_avg_dict[name])
However, this doesn't work. Any help?
I'm 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 > 0to check that an array is not empty.
Solution 1:[1]
You need to iterate over the myList and check if a country in it is in countryDict:
for country in myList:
if country in countryDict:
print(country, countryDict[country])
Output:
France 66
Brazil 120
Armenia 99
Solution 2:[2]
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
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)
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Corne14 |
| Solution 3 | Xinthral |
