Home > OS >  Search for a value in nested dictionary
Search for a value in nested dictionary

Time:04-21

I'd like to search a list of dictionaries below for a particular key-value pair. In this case administrative_area_level_1 and get the value of short_name key from that dictionary.

The contents of the list varies, therefore I cannot simply access it with an index, e.g. I can't do something like s[0]['address_components'][4].

Here's a sample list of dictionaries:

[{'address_components': [{'long_name': '5555',
    'short_name': '5555',
    'types': ['street_number']},
   {'long_name': 'East 14th Street',
    'short_name': 'E 14th St',
    'types': ['route']},
   {'long_name': 'Tucson',
    'short_name': 'Tucson',
    'types': ['locality', 'political']},
   {'long_name': 'Pima County',
    'short_name': 'Pima County',
    'types': ['administrative_area_level_2', 'political']},
   {'long_name': 'Arizona',
    'short_name': 'AZ',
    'types': ['administrative_area_level_1', 'political']},
   {'long_name': 'United States',
    'short_name': 'US',
    'types': ['country', 'political']},
   {'long_name': '85711', 'short_name': '85711', 'types': ['postal_code']}],
  'formatted_address': '5555 E 14th St, Tucson, AZ 85711, USA',
  'geometry': {'bounds': {'northeast': {'lat': 32.2180021,
     'lng': -110.8732351},
    'southwest': {'lat': 32.2169439, 'lng': -110.8750912}},
   'location': {'lat': 32.2175302, 'lng': -110.874105},
   'location_type': 'GEOMETRIC_CENTER',
   'viewport': {'northeast': {'lat': 32.2188219802915,
     'lng': -110.8728141697085},
    'southwest': {'lat': 32.2161240197085, 'lng': -110.8755121302915}}},
  'place_id': 'ChIJM8Ct8ZVv1oYRG5lGDi',
  'types': ['premise']}]

How can get the following expected output?

'AZ'

CodePudding user response:

You can use .get() with .filter() to ignore any dicitonaries that don't have a types key and don't have the target string in the types list. From there, you can directly access the short_name key:

Here is a code snippet that finds all the short_names of all the dictionaries that satisfy the aforementioned properties:

target = 'administrative_area_level_1'
retained_items = list(filter(lambda x: target in x.get('types', []),
    data[0]['address_components']))

for item in retained_items:
    print(item['short_name'])

This outputs:

AZ

as desired.

CodePudding user response:

This way you can achieve it, where data is your given list of dictionaries.

target_key = 'administrative_area_level_1'
target_value_of = 'short_name'
for i in data:
    if(i['address_components']):
        for d in i['address_components']:
            if(target_key in d['types']):
                print(d[target_value_of])
  • Related