Helfen Sie mir, den Fehler anhand des Titels zu lösen. Ich habe versucht, den countryCode basierend auf country_name in der Variable 'rv' zu drucken. und dann versuche ich, countryCode abzurufen und dort habe ich den Fehler erhalten
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)
country_found
ist eine Liste, aber Sie versuchen, ein Element über einen String-Index abzurufen:
country_found['countryCode']
Wahrscheinlich wollten Sie das erste Ergebnis eines Matches erzielen:
country_code = country_found[0]['countryCode'] if country_found else default_country_code
Müssen Sie eigentlich das Ergebnis als Liste haben, was wäre, wenn Sie einfach next()
verwenden würden:
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
Wenn ich Ihre Frage richtig bekomme, möchten Sie vielleicht unten nachschauen.
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