我有以下词典:
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']
答案 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']