Reputation: 5823
I have following dict:
defaultdict(<type 'dict'>,
{'11': {('extreme_fajita', 'jalapeno_poppers'): '4',('test12', 'test14'): '5'},
'10': {('jalapeno_poppers', 'test', ): '2', ('test2',): '3', ('test14',): '5'}
}
And I want to search on based on inner key i.e ('test2',)
I should get the value from inner dictionary and parent key (outer key)
i.e searching for ('test2',)
I should get get ['10', '3']
or whole like ['10', '('test2', )', '3']
Upvotes: 1
Views: 975
Reputation: 551
I'm going to assume your defaultdict
looks like:
defaultdict = {'11': {('extreme_fajita', 'jalapeno_poppers'): '4',('test12', 'test14'): '5'}, '10': {('jalapeno_poppers', 'test2', ): '2', ('test2',): '3', ('test14',): '5'} }
If that's the case, then you can use:
searchValue = 'test2'; found = []
for masterkey,mastervalue in defaultdict.iteritems():
for childkey,childvalue in mastervalue.iteritems():
if searchValue in childkey:
found.append(childvalue)
print found
Upvotes: 2
Reputation: 4318
Dictionary is not ordered so you will not get in the order as '2','3' instead you can get all values from the dictionary where 'test2' found. I have following code for this:
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)
Output:
test2 found at:: 11->10-> ('test2',)
Value of test2:: 3
Values in parent:: ['2', '5', '3']
Upvotes: 0