简体   繁体   中英

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 :

for country in myList:
    if country in countryDict:
        print(country, countryDict[country])

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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