我在下面有这个词典
metric_app_mapper = \
{"appdynamics":
{
"avgresptime": ["average response time", "avgresptime", "avgrest", "art"],
"callspermin": ["calls per minute", "callspermin", "calls/min"],
"allapps": ["all apps", "all apps info", "all applications"]
},
"another_software":
{
"metric": ["synonyms"]
}
}
我正在尝试获取值“art”的关键字。但我只能搜索“art”的值或它所在的列表。以下是我的代码
search_key = [j for i in metric_app_mapper.values() for j in i.values() for k in j if k == "art"]
print("Key found", search_key)
我得到给定值的列表
Key found [['average response time', 'avgresptime', 'avgrest', 'art']]
如果我为该值找到的给定列表中的“avgresptime”,如何获取相关密钥,依次为“Appdynamics”给出密钥?有没有更好的方法来做到这一点,因为我的方法涉及O(n ^ 3)运行时间?
答案 0 :(得分:1)
这是一个产生关键"路径"的递归解决方案。 keys + (k,)
语法在Python版本> = 3.5中可用,您也可以使用from collections.abc import Collection
def find(dictionary, value, keys=()):
for k, v in dictionary.items():
path_to = (*keys, k)
if v == value:
yield path_to
elif isinstance(v, dict):
yield from find(v, value, path_to)
elif isinstance(v, Collection): # might make more sense to use Container, I'm not sure
if value in v:
yield path_to
print(list(find(metric_app_mapper, 'art')))
# [('appdynamics', 'avgresptime')]
{{1}}
答案 1 :(得分:0)
作为对@Jon Clements代码的一点修改,这就是我需要的东西。
interpreted_tool = [[k1, k2] for k1, v1 in metric_app_mapper.items() for k2, v2 in v1.items() for v3 in v2 if v3 == metric]
答案 2 :(得分:0)
试试这个: -
for i,j in metric_app_mapper.items():
for k,l in j.items():
if "art" in l:
print(k,i)