I need to write a function which is doing following work

Find a string as value in a dictionary of dictionaries and return its key (1st key if found in main dictionary, 2nd key if found in sub dictionary).

Source Code

Here is the function which I try to implement, but it works incorrect as I can't find any answer of how to convert list into dictionary as in this case the following error occurs

for v, k in l: ValueError: need more than 1 value to unpack

def GetKeyFromDictByValue(self, dictionary, value_to_find):
    """"""

    key_list = [k for (k, v) in dictionary.items() if v == value_to_find]
    if key_list.__len__() is not 0:
        return key_list[0]
    else:
        l = [s for s in dictionary.values() if  ":" in str(s)]
        d = defaultdict(list)
        for 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 do this on Python 2.5

有帮助吗?

解决方案

You created a list of only the dictionary values, but then try to loop over it as if it already contains both keys and values of those dictionaries. Perhaps you wanted to loop over each matched dictionary?

l = [v for v in dictionary.values() if  ":" in str(v)]
d = defaultdict(list)
for subdict in l:
    for k, v in subdict.items():

I'd instead flatten the structure:

def flatten(dictionary):
    for key, value in dictionary.iteritems():
        if isinstance(value, dict):
            # recurse
            for res in flatten(value):
                yield res
        else:
            yield key, value

then just search:

def GetKeyFromDictByValue(self, dictionary, value_to_find):
    for 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'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top