Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I search for specific keys in this nested dictionary in Python?

I am new to programming and I'm trying to extract values from the Amazon MWS API. It returns the biggest nested dictionary I've seen and I'm having trouble figuring out how to loop through it to find the value I need.

Example:

{'Products': {'Product': {'AttributeSets': {'ItemAttributes': {'Binding': {'value': 'Video '
                                                                                'Game'},
                                                           'Brand': {'value': 'Nintendo'},
                                                           'Color': {'value': 'blue'},
                                                           'ESRBAgeRating': {'value': 'Everyone'},
                                                           'HardwarePlatform': {'value': 'Android/iOS'},
                                                           'IsAdultProduct': {'value': 'false'},
                                                           'ItemDimensions': {'Height': {'Units': {'value': 'inches'},
                                                                                         'value': '5.00'},
                                                                              'Length': {'Units': {'value': 'inches'},
                                                                                         'value': '5.00'},
                                                                              'Weight': {'Units': {'value': 'pounds'},
                                                                                         'value': '0.10'},
                                                                              'Width': {'Units': {'value': 'inches'},
                                                                                        'value': '2.00'}},
                                                           'Label': {'value': 'Nintendo'},
                                                           'Languages': {'Language': {'Name': {'value': 'english'},
                                                                                      'Type': {'value': 'Unknown'}}},
                                                           'ListPrice': {'Amount': {'value': '34.99'},
                                                                         'CurrencyCode': {'value': 'USD'}},
                                                           'Manufacturer': {'value': 'Nintendo'},
                                                           'Model': {'value': 'PMCAPBAA'},
                                                           'OperatingSystem': [{'value': 'Not '
                                                                                         'Machine '
                                                                                         'Specific'},
                                                                               {'value': 'Android/iOS'}],
                                                           'PackageDimensions': {'Height': {'Units': {'value': 'inches'},
                                                                                            'value': '1.00'},
                                                                                 'Length': {'Units': {'value': 'inches'},
                                                                                            'value': '5.10'},
                                                                                 'Weight': {'Units': {'value': 'pounds'},
                                                                                            'value': '0.04'},
                                                                                 'Width': {'Units': {'value': 'inches'},
                                                                                           'value': '2.90'}},
                                                           'PackageQuantity': {'value': '1'},
                                                           'PartNumber': {'value': 'PMCAPBAA'},
                                                           'Platform': [{'value': 'Not '
                                                                                  'Machine '
                                                                                  'Specific'},
                                                                        {'value': 'Android'},
                                                                        {'value': 'iOS'},
                                                                        {'value': 'Nintendo '
                                                                                  'Wii'}],
                                                           'ProductGroup': {'value': 'Video '
                                                                                     'Games'},
                                                           'ProductTypeName': {'value': 'VIDEO_GAME_ACCESSORIES'},
                                                           'Publisher': {'value': 'Nintendo'},
                                                           'ReleaseDate': {'value': '2016-09-16'},
                                                           'SmallImage': {'Height': {'Units': {'value': 'pixels'},
                                                                                     'value': '75'},
                                                                          'URL': {'value': 'http://ecx.images-amazon.com/images/I/41%2B1-PwEz4L._SL75_.jpg'},
                                                                          'Width': {'Units': {'value': 'pixels'},
                                                                                    'value': '75'}},
                                                           'Studio': {'value': 'Nintendo'},
                                                           'Title': {'value': 'Nintendo '
                                                                              'Pokemon '
                                                                              'Go '
                                                                              'Plus'},
                                                           'lang': {'value': 'en-US'}}},
                      'Identifiers': {'MarketplaceASIN': {'ASIN': {'value': 'B01H482N6E'},
                                                          'MarketplaceId': {'value': 'ATVPDKIKX0DER'}}},
                      'Relationships': {},
                      'SalesRankings': {'SalesRank': [{'ProductCategoryId': {'value': 'video_games_display_on_website'},
                                                       'Rank': {'value': '35'}},
                                                      {'ProductCategoryId': {'value': '14218821'},
                                                       'Rank': {'value': '1'}},
                                                      {'ProductCategoryId': {'value': '471304'},
                                                       'Rank': {'value': '22'}}]}}}}

How can I find the value of 'Title' or what would be the best way to find the value 'Title' from this dictionary?

When I try to implement similar recursive solutions I found on Stackoverflow, I get a None value.

I've tried:

def recursive_lookup(k, d):
    if k in d:
        return d[k]
    for v in d.values():
        if isinstance(v, dict):
            return recursive_lookup(k, v)
    return None

print(recursive_lookup('Title', productData.parsed))
like image 946
Youn Jung Chung Avatar asked Apr 05 '18 01:04

Youn Jung Chung


People also ask

How do you check if a certain key is in a dictionary Python?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do you access nested dictionary items in Python?

To access element of a nested dictionary, we use indexing [] syntax in Python.

How do you check if a value is in a nested dictionary Python?

Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).

How do I search for a key in Python?

To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print('Dogs found!') # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.


2 Answers

The problem with your code is that you are not backtracking to other dictionaries. You don't loop through all the items before you return. By returning you cut off your loop.

The code below loops through all of the dicts and doesn't return until it has either found the key or it has checked all the dicts and found nothing.

def recursive_lookup(k, d):
    if k in d: return d[k]
    for v in d.values():
        if isinstance(v, dict):
            a = recursive_lookup(k, v)
            if a is not None: return a
    return None
like image 83
Primusa Avatar answered Sep 21 '22 19:09

Primusa


You can use dict.items at each recursive call:

def get_value(d, target = 'Title'):
  val = filter(None, [[b] if a == target else get_value(b) if isinstance(b, dict) else None for a, b in d.items()])
  return [i for b in val for i in b]

print(get_value(structure))

Output:

[{'value': 'Nintendo Pokemon Go Plus'}]
like image 26
Ajax1234 Avatar answered Sep 21 '22 19:09

Ajax1234