python - 根据值从嵌套字典中检索键,其中键名未知
问题描述
我有以下字典:
{
'foo': {
'name': 'bar',
'options': None,
'type': 'qux'
},
'baz': {
'name': 'grault',
'options': None,
'type': 'plugh'
},
}
顶级键的名称在运行时是未知的。我无法弄清楚如何获取值为 的顶级键的type
名称plugh
。我尝试过各种迭代器、循环、推导等,但我对 Python 不是很好。任何指针将不胜感激。
解决方案
试试这个:
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
推荐阅读
- .net-core - 具有提交按钮的 .cshtml 页面上的 blazor 组件
- python - 从 flask_pymongo 导入 PyMongo ModuleNotFoundError 出错:没有名为“flask_pymongo”的模块
- rest - OData v4 扩展多个一对多
- flutter - 文本溢出时如何淡化文本?
- r - R: as.name() - 不支持的类型符号错误”
- bluetooth - 如何检查 BLE 广告是否已启用(HCI)
- c# - GitLab 提供了错误的 C# 代码编码。解决此问题的方法
- amazon-web-services - 如何使用 CLI 访问 ec2 windows 实例中的 s3 存储桶
- quill.io - 是否可以使用 IN 使用 Quill 更新多行
- typescript - Pulumi 在运行时获取 kubernetes 上下文