python - Find a string as value in a dictionary of dictionaries and return its key -
i need write function doing following work
find string value in dictionary of dictionaries , return key (1st key if found in main dictionary, 2nd key if found in sub dictionary).
source code
here function try implement, works incorrect i can't find answer of how convert list dictionary in case following error occurs
for v, k in l: valueerror: need more 1 value unpack
def getkeyfromdictbyvalue(self, dictionary, value_to_find): """""" key_list = [k (k, v) in dictionary.items() if v == value_to_find] if key_list.__len__() not 0: return key_list[0] else: l = [s s in dictionary.values() if ":" in str(s)] d = defaultdict(list) v, k in l: d[k].append(v) print d dict = {'a': {'a1': 'a2'}, "aa": "aa1", 'aaa': {'aaa1': 'aaa2'}} print getkeyfromdictbyvalue(dict, "a2")
i must on python 2.5
you created list of only dictionary values, try loop on if contains both keys , values of dictionaries. perhaps wanted loop on each matched dictionary?
l = [v v in dictionary.values() if ":" in str(v)] d = defaultdict(list) subdict in l: k, v in subdict.items():
i'd instead flatten structure:
def flatten(dictionary): key, value in dictionary.iteritems(): if isinstance(value, dict): # recurse res in flatten(value): yield res else: yield key, value
then search:
def getkeyfromdictbyvalue(self, dictionary, value_to_find): key, value in flatten(dictionary): if value == value_to_find: return key
demo:
>>> sample = {'a': {'a1': 'a2'}, "aa": "aa1", 'aaa': {'aaa1': 'aaa2'}} >>> getkeyfromdictbyvalue(none, sample, "a2") 'a1'
Comments
Post a Comment