在python中嵌套dict,基于内键搜索得到内部值和父键

2024-05-23 18:59:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下口述:

defaultdict(<type 'dict'>, 
{'11': {('extreme_fajita', 'jalapeno_poppers'): '4',('test12', 'test14'): '5'}, 
 '10': {('jalapeno_poppers', 'test', ): '2', ('test2',): '3', ('test14',): '5'}
}

我想基于内部键进行搜索,即('test2',)我应该从内部字典和父键(外部键)中获取值

即搜索('test2',)我应该得到['10', '3']或类似{}的整体


Tags: test字典typedict整体test2extreme口述
2条回答

我假设你的defaultdict看起来像:

defaultdict = {'11': {('extreme_fajita', 'jalapeno_poppers'): '4',('test12', 'test14'): '5'}, '10': {('jalapeno_poppers', 'test2', ): '2', ('test2',): '3', ('test14',): '5'} }

如果是这样,那么您可以使用:

^{pr2}$

字典未排序,因此您不会按“2”和“3”的顺序获取,而是可以从“test2”所在的字典中获取所有值。我有以下代码:

def getKeys(d1, path="", lastDict=list()):
    for k in d1.keys():
        if type(k) is tuple:
            if 'test2' in k:
                print "test2 found at::", path + "->" , k
                print "Value of test2::", d1[k]
                print "Values in parent::", [kl for kl in lastDict[len(lastDict)-1].values()]
        elif type(d1[k]) is dict:
            lastDict.append(d1[k])
            if path == "":
                path = k
            else:
                path = path + "->" + k
            getKeys(d1[k], path)

d = {'11': {('extreme_fajita', 'jalapeno_poppers'): '4',('test12', 'test14'): '5'}, '10': {('jalapeno_poppers', 'test', ): '2', ('test2',): '3', ('test14',): '5'}}
getKeys(d)

输出:

^{pr2}$

相关问题 更多 >