python字典遍历登录程序,如何做到这一点 - python字典遍历和搜索

博客讨论了如何在具有嵌套结构的字典中,通过给定的ID有效地找到目标字典。提供了使用Visitor模式遍历字典的Python代码示例,该代码能够递归地搜索具有最多4级深度的嵌套,并在找到匹配ID时打印路径和元素。此方法可以修改为生成器以处理大型数据结构。
摘要由CSDN通过智能技术生成

I have nested dictionaries:

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

given an id - one of all the ids like 4130 to 4130-2-2.

whats the easiest way to navigate to the correct dictionary?

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

non xml approaches please.

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

Edit(2): Fixed the code.

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

解决方案

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

You'd use it like this.

walkDict( myDict, filterFor )

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

You'd use it in a for loop.

for path, attrDict in walkDictIter( aDict ):

# process attrDict...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值