0

I am trying to extract the name of the city from a google maps API requests. Here is the result of the request:

[{'long_name': 'Chandigarh',
  'short_name': 'Chandigarh',
  'types': ['locality', 'political']},
 {'long_name': 'Chandigarh',
  'short_name': 'CH',
  'types': ['administrative_area_level_1', 'political']},
  {'long_name': 'India', 'short_name': 'IN', 'types': ['country', 'political']},
 {'long_name': '160022', 'short_name': '160022', 'types': ['postal_code']}]

I want to extract the name of the city knowing that it is not always the 1st one:

    print(x['long_name'][0] for x in geocode_result[0].get('address_components') if x.get('types')[0]=='locality')

But this give me a generator:

<generator object <genexpr> at 0x0000021FB038F3B8>

However when I do a for loop, its ok:

for x in geocode_result[0].get('address_components'):
if x.get('types')[0]=='locality':
    print(x.get('long_name'))
Chandigarh

Do you see what is the problem in the one liner?

Thank you!

Wendy
  • 791
  • 1
  • 5
  • 8

1 Answers1

1

Comprehensions return a generator unless surrounded in [], so just add those characters:

print([x['long_name'][0] for x in geocode_result[0].get('address_components') if x.get('types')[0]=='locality'])
cdhowie
  • 158,093
  • 24
  • 286
  • 300