python - 检索满足某些条件的字典
问题描述
我有一本字典,如下所示:
x = {
"Student": [
{
"tags": {
"name": "Alex",
"class": "Biology",
"gender": "male",
},
"Nationality": "",
"Test Score": 10.0,
"Exam Score": 70.0,
},
{
"tags": {
"id": "A123",
"height": "170",
"age": "15",
},
"Nationality": "",
"Test Score": 20.0,
"Exam Score": 80.0,
},
],
}
我想获得上面数据模式的测试分数和考试分数,其中有一个带有键“标签”的嵌套字典,键是“id”、“height”和“age”
所以期望值应该是“Test Score”=20.0 and “Exam Score”=80.0
我已经尝试了以下实现,但它似乎只检查“学生”列表中的第一个值(长度为 2),但我需要它来检查列表中的所有项目(在本例中为两个项目)。
search_tag = ["id", "height", "age"]
val_list = []
if all([t in search_tag for t in x["Student"][0]["tags"].keys()]):
val_list.append(x["Student"][0]["Test Score"])
val_list.append(x["Student"][0]["Exam Score"])
解决方案
您可以将set
您的密钥与.keys()
:
x = {
"Student": [
{
"tags": {
"name": "Alex",
"class": "Biology",
"gender": "male",
},
"Nationality": "",
"Test Score": 10.0,
"Exam Score": 70.0,
},
{
"tags": {
"id": "A123",
"height": "170",
"age": "15",
},
"Nationality": "",
"Test Score": 20.0,
"Exam Score": 80.0,
},
],
}
to_search = {"age", "id", "height"}
for student in x["Student"]:
if student["tags"].keys() == to_search:
print(student["Test Score"])
print(student["Exam Score"])
印刷:
20.0
80.0
推荐阅读
- 3d - 如何从 3D 对象获取 X、Y、Z 的坐标?
- html - 当我运行我的 html 代码时,它会在赞助商部分之后跳转吗?
- excel-formula - 在 Excel 单元格引用中使用日期
- excel - 使用VBA根据excel单元格内容更改字体类型
- python-3.x - 如何将熊猫数据框保存到文件位置,然后将该文件添加到电子邮件附件
- html - 您如何禁用删除 atom-beautify 中的多个空格?
- python - How to perform operation over each dictionary in column?
- msys2 - How to make the shell start at a specific folder with MSYS2?
- typescript - MSGraph - 是否可以对从 API 调用的属性进行切片?
- homebrew - Homebrew list packages I have installed