Home > Back-end >  Find if a value in a list exists in a dictionary in python
Find if a value in a list exists in a dictionary in python

Time:12-04

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.

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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

  • Related