python - need to iterate through dictionary to find slice of string -


i have function accepts dictionary parameter(which returned function works). function supposed ask string input , through each element in dictionary , see if in there. dictionary 3 letter acronym: country i.e:afg:afghanistan , on , forth. if put in 'sta' string, should append country has slice united states, afghanistan, costa rica, etc initialized empty list , return said list. otherwise, returns [not found]. returned list should this:[ [‘code’,’country’], [‘usa’,‘united states’],[‘cri’,’costa rica’],[‘afg’,’afganistan’]] etc. here's code looks far:

def findcode(countries):     some_strng = input("give me country search using 3 letter acronym: ")     reference =['code','country']     code_country= [reference]     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 keeps returning ['not found']

your code:

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

should be:

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

you need check each value string, assuming countries in values , not keys.

also final return statement:

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

should this, there many ways check this:

if len(code_country) == 1   code_country.append( ['not found']) 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -