如何在Python的此嵌套字典中搜索特定的键? [英] How can I search for specific keys in this nested dictionary in Python?

查看:98
本文介绍了如何在Python的此嵌套字典中搜索特定的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,我正尝试从Amazon MWS API提取值.它返回了我所见过的最大的嵌套字典,但是我在弄清楚如何遍历它来查找所需的值时遇到了麻烦.

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.

示例:

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

如何找到'Title'的值,或者从该词典中找到'Title'值的最佳方法是什么?

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

当我尝试实现在Stackoverflow上发现的类似递归解决方案时,我得到了None值.

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

我尝试过:

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

这篇关于如何在Python的此嵌套字典中搜索特定的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆