error list indices must be integers or slices, not str

14,639

country_found is a list, but you are trying to get an item by a string index:

country_found['countryCode']

You've probably meant to get the first result of a match:

country_code = country_found[0]['countryCode'] if country_found else default_country_code

But, do you actually need to have the result as a list, what if you would just use next():

result = take_first(lambda e: e['name'].lower() == country_lower, 
                    countries['DATA']['data'])
try:
    country_code = next(result)['countryCode']
except StopIteration:
    country_code = default_country_code
Share:
14,639
Rachman Fauzan
Author by

Rachman Fauzan

Updated on June 04, 2022

Comments

  • Rachman Fauzan
    Rachman Fauzan almost 2 years

    Based on the title, help me solve the error. i've tried to print the countryCode based on country_name which is in 'rv' variable. country_found is list of data that have the same value on countries list, and then i try to retrieve countryCode and there i got the error

    rv = "Indonesia"
    country_lower = rv.lower()
    countries = {
      "DATA": {
        "data": [{
            "countryId": "26",
            "countryCode": "AU",
            "name": "Australia"
        }, {
            "countryId": "17",
            "countryCode": "ID",
            "name": "Indonesia"
        }]
       }
    } 
    def take_first(predicate, iterable):
     for element in iterable:
        if predicate(element):
            yield element
            break
    
    country_found = list(
     take_first(
        lambda e: e['name'].lower() == country_lower, 
        countries['DATA']['data']
     )
    )
    
    default_country_code = 'US'
    country_code = (
      country_found['countryCode'] 
      if country_found 
      else default_country_code
    )
    print (country_code)