简体   繁体   中英

need to iterate through dictionary to find slice of string

I have a function that accepts a dictionary as a parameter(which is returned from another function that works). This function is supposed to ask for a string as input and look through each element in the dictionary and see if it is in there. The dictionary is basically Three letter Acronym: country ie:AFG:Afghanistan and so on and so forth. If I were to put in 'sta' as my string, it should append any country with that has that slice like united STAtes, AfghaniSTAn, coSTA rica, etc to an initialized empty list and then return said list. otherwise, it returns [NOT FOUND]. returned list should look like this:[ ['Code','Country'], ['USA','United States'],['CRI','Costa Rica'],['AFG','Afganistan']] etc. here's what my code looks like thus far:

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']

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 to check each value for the string, assuming your countries are in the values and not the keys.

Also your final return statement:

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

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

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

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