简体   繁体   中英

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))

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

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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM