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

查看:39
本文介绍了如何遍历和搜索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 -所有 id 之一,例如 4130 4130-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?

就像给定的 id 4130-2-1 一样,它应该使用 key = key5

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

请使用非xml方法.

编辑(1):嵌套在 1 4 级别之间,但是在解析之前我知道嵌套.

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

编辑(2):修改了代码.

**编辑(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 )

这可以变成生成器,而不是 Visitor ;它会 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天全站免登陆