You need to iterate over the dictionary to find a fragment of a string

I have a function that takes a dictionary as a parameter (which is returned from another function that works). It is assumed that this function queries the string as input and looks at each element in the dictionary and sees if it is there. Dictionary mainly Three letters Acronym: country ie: AFG: Afghanistan, etc. Etc. If I had to put "sta" as my string, it should add any country that has such a fragment as the combined STAtes, afaniSTAn, coSTA rica, etc., to the initialized empty list, and then return the specified list. otherwise, it returns [NOT FOUND]. the returned list should look like this: [['Code, Country], [' USA, 'United States], [' CRI, Costa Rica], ['AFG, Afganistan]], etc. here is what my code looks like:

def findCode(countries): some_strng = input("Give me a country to search for using a three letter acronym: ") reference =['Code','Country'] code_country= [reference] for key in countries: if some_strng in countries: code_country.append([key,countries[key]]) if not(some_strng in countries): code_country.append( ['NOT FOUND']) print (code_country) return code_country 

my code just keeps returning ['NOT FOUND']

+4
source share
1 answer

Your code:

 for key in countries: if some_strng in countries: code_country.append([key,countries[key]]) 

it should be:

 for key,value in countries.iteritems(): if some_strng in value: code_country.append([key,countries[key]]) 

You need to check each value for a row if your countries are in values, not in keys.

Also your final return statement:

 if not(some_strng in countries): code_country.append( ['NOT FOUND']) 

There must be something like this, there are many ways to check this:

 if len(code_country) == 1 code_country.append( ['NOT FOUND']) 
+5
source

Source: https://habr.com/ru/post/1491950/


All Articles