如何遍历和搜索 python 字典? [英] How do I traverse and search a python dictionary?

查看:20
本文介绍了如何遍历和搜索 python 字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有嵌套字典:

{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'},
          u'key1': {'attrs': {'entity': 'r',
                              'hash': '34njasd3h43b4n3',
                              'id': '4130-1'},
                    u'key2': {'attrs': {'entity': 'c',
                                        'hash': '34njasd3h43bdsfsd4n3',
                                        'id': '4130-1-1'}}},
          u'key3': {'attrs': {'entity': 'r',
                              'hash': '34njasasasd3h43b4n3',
                              'id': '4130-2'},
                    u'key4': {'attrs': {'entity': 'c',
                                        'hash': '34njawersd3h43bdsfsd4n3',
                                        'id': '4130-2-1'}},
                    u'key5': {'attrs': {'entity': 'c',
                                        'hash': '34njawersd3h43bdsfsd4n3',
                                        'id': '4130-2-2'}}}},
 'someohterthing': 'someothervalue',
 'something': 'somevalue'}

给定一个 id - 所有 ids 之一,例如 41304130-2-2.
导航到正确字典的最简单方法是什么?

given an id - one of all the ids like 4130 to 4130-2-2.
whats the easiest way to navigate to the correct dictionary?

如果给定的 id4130-2-1 那么它应该通过 key=key5

Like if the given id is 4130-2-1 then it should reach the dictionary with key=key5

非 xml 方法请.

Edit(1): 嵌套在 14 层之间,但我在解析之前就知道嵌套.

Edit(1): The nesting is between 1 to 4 levels, but I know the nesting before I parse.

Edit(2):修正了代码.

**Edit(3):**再次修正了 ids 的字符串值的代码.请原谅造成的混乱.这是最后的我希望:)

**Edit(3):**Fixed code again for string values of ids. Please excuse for the confusion created. This is final I hope :)

推荐答案

您的结构不规则,令人不快.这是一个带有 Visitor 函数的版本,该函数遍历 attrs 子词典.

Your structure is unpleasantly irregular. Here's a version with a Visitor function that traverses the attrs sub-dictionaries.

def walkDict( aDict, visitor, path=() ):
    for  k in aDict:
        if k == 'attrs':
            visitor( path, aDict[k] )
        elif type(aDict[k]) != dict:
            pass
        else:
            walkDict( aDict[k], visitor, path+(k,) )

def printMe( path, element ):
    print path, element

def filterFor( path, element ):
    if element['id'] == '4130-2-2':
        print path, element

你会像这样使用它.

walkDict( myDict, filterFor )

这可以变成一个生成器而不是一个访问者;它会yield path, aDict[k] 而不是调用visitor 函数.

This can be turned into a generator instead of a Visitor; it would yield path, aDict[k] instead of invoking the visitor function.

你会在 for 循环中使用它.

You'd use it in a for loop.

for path, attrDict in walkDictIter( aDict ):
    # process attrDict...

这篇关于如何遍历和搜索 python 字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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