错误清单索引必须是整数或切片,而不是字符串。

4

基于标题,帮我解决这个错误。 我尝试根据'rv'变量中的country_name打印countryCode。 country_found是一个具有相同值的国家列表数据, 然后我尝试检索countryCode,结果出现了错误。

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)
2个回答

4

country_found 是一个列表,但你正在试图通过字符串索引获取其项:

country_found['countryCode']

您可能想获取匹配的第一个结果:
country_code = country_found[0]['countryCode'] if country_found else default_country_code

但是,你真的需要将结果作为一个列表吗?如果你只使用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

0
如果我理解你的问题正确,以下是你可能想要了解的内容。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接