python中嵌套的dict,基于内键搜索获取内部值和父键

时间:2014-02-28 10:44:53

标签: python dictionary nested key

我有以下词典:

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']或整像['10', '('test2', )', '3']

2 个答案:

答案 0 :(得分:2)

我假设你的defaultdict看起来像是:

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

如果是这种情况,那么您可以使用:

searchValue = 'test2'; found = []
for masterkey,mastervalue in defaultdict.iteritems():
    for childkey,childvalue in mastervalue.iteritems():
        if searchValue in childkey:
            found.append(childvalue)
print found

答案 1 :(得分:0)

字典不是有序的,因此您不会按顺序排列为'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)

输出:

test2 found at:: 11->10-> ('test2',)
Value of test2:: 3
Values in parent:: ['2', '5', '3']