首页 > 解决方案 > 根据值从嵌套字典中检索键,其中键名未知

问题描述

我有以下字典:

{
  'foo': {
    'name': 'bar',
    'options': None,
    'type': 'qux'
  },
  'baz': {
    'name': 'grault',
    'options': None,
    'type': 'plugh'
  },
}

顶级键的名称在运行时是未知的。我无法弄清楚如何获取值为 的顶级键的type名称plugh。我尝试过各种迭代器、循环、推导等,但我对 Python 不是很好。任何指针将不胜感激。

标签: pythondictionary

解决方案


试试这个:

for key, inner_dict in dict_.items():
    if inner_dict['type'] == 'plugh':
        print(key)

或者,如果您使用一个衬垫来获得与条件匹配的第一个键:

key = next(key for key, inner_dict in dict_.items() if inner_dict['type'] == 'plugh')
print(key)

输出:

baz

推荐阅读