python - 在有特定键值对的列表中获取字典
问题描述
假设我在列表中有这本字典:
[
{
"Name": "Person",
"Confidence": 97.56156921386719,
"Instances": [
{
"BoundingBox": {
"Width": 0.6137702465057373,
"Height": 0.9175498485565186,
"Left": 0.22297996282577515,
"Top": 0.0739903450012207
},
"Confidence": 94.51961517333984
},
{
"BoundingBox": {
"Width": 0.46570318937301636,
"Height": 0.6405649781227112,
"Left": 0.11447866261005402,
"Top": 0.34079012274742126
},
"Confidence": 82.2153549194336
}
],
"Parents": []
},
{
"Name": "Human",
"Confidence": 97.56156921386719,
"Instances": [],
"Parents": []
},
{
"Name": "Clothing",
"Confidence": 91.08417510986328,
"Instances": [],
"Parents": []
}
}]
如何仅检索具有键值“名称”:“服装”的字典?是否可以从字典中检索它?“服装”键可能出现在列表的任何部分。
{
"Name": "Clothing",
"Confidence": 91.08417510986328,
"Instances": [],
"Parents": []
}
解决方案
您可以使用以下代码获取具有Name
的每个项目Clothing
:
names = [
{
"Name": "Person",
"Confidence": 97.56156921386719,
"Instances": [
{
"BoundingBox": {
"Width": 0.6137702465057373,
"Height": 0.9175498485565186,
"Left": 0.22297996282577515,
"Top": 0.0739903450012207
},
"Confidence": 94.51961517333984
},
{
"BoundingBox": {
"Width": 0.46570318937301636,
"Height": 0.6405649781227112,
"Left": 0.11447866261005402,
"Top": 0.34079012274742126
},
"Confidence": 82.2153549194336
}
],
"Parents": []
},
{
"Name": "Human",
"Confidence": 97.56156921386719,
"Instances": [],
"Parents": []
},
{
"Name": "Clothing",
"Confidence": 91.08417510986328,
"Instances": [],
"Parents": []
}
]
for name in names:
if name['Name'] == 'Clothing':
print(name)
如果您希望它简短,可以使用以下代码:
x = [y for y in names if name['Name'] == 'Clothing']
推荐阅读
- ios - 在“NavigationLink”上引用初始化程序“init(destination:label:)”
- sql - Postgres 左外连接不适用于 NULLS
- sql-server - 无法连接另一个 sql server 实例
- r - R中字符串的模糊逻辑
- typescript - 误解还是错误?映射类型的问题
- express - 有人可以告诉我在哪里可以写我的 bcrypt 散列函数吗?
- sql - 使用带有 ORDER BY 的 SQL Server 查找累积总和
- c# - 如何从两个日期之间的差异中删除特定的时间段
- c - 在 C 中实现构造函数的正确方法
- php - 无法使用散列密码登录 - Mysqli PHP