在字典字典中查找字符串作为值并返回其键 (如果在主词典中找到第一个键,则在子词典中找到第二个键)。
这是我尝试实现的功能,但它的工作原理不正确我找不到如何将列表转换为字典的任何答案,因为在这种情况下会发生以下错误
表示v,k表示l: ValueError:解包需要多于1个值
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")
我必须在Python 2.5上执行此操作
答案 0 :(得分:4)
您创建了仅字典值的列表,但随后尝试循环遍历它,就好像它已包含这些字典的键和值一样。也许你想循环遍历每个匹配的字典?
l = [v for v in dictionary.values() if ":" in str(v)]
d = defaultdict(list)
for subdict in l:
for k, v in subdict.items():
我反而展平结构:
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
然后只搜索:
def GetKeyFromDictByValue(self, dictionary, value_to_find):
for key, value in flatten(dictionary):
if value == value_to_find:
return key
演示:
>>> sample = {'a': {'a1': 'a2'}, "aa": "aa1", 'aaa': {'aaa1': 'aaa2'}}
>>> GetKeyFromDictByValue(None, sample, "a2")
'a1'