Error List Indices Must Be Integers Or Slices, Not Str
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 v
Solution 1:
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
Solution 2:
If I get your question correctly, below is what you might want to look into.
default_country_code = 'US'
print(country_found) # ==> list [{'countryId': '17', 'name': 'Indonesia', 'countryCode': 'IN'}]
print(country_found[0]) # ==> dictionary {'countryId': '17', 'name': 'Indonesia', 'countryCode': 'IN'}
print(country_found[0].get('countryCode',default_country_code)) # get countryCode. If countryCode is not there, get the default_country_code
Post a Comment for "Error List Indices Must Be Integers Or Slices, Not Str"