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,
                
        },
              ],
    }

我想获得上面数据模式的考试成绩和考试成绩,其中有一个嵌套字典,键“tag”的键为“id”、“height”和“age”

因此期望值应该是“考试成绩”=20.0 和“考试成绩”=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

https://stackoverflow.com/questions/68693857/

相关文章:

javascript - 如何使用 Axios 拦截器向响应添加一些 header ?

string - 函数不想使用函数参数返回字符串切片

python - 根据python中另一个字符串元素的数量删除字符串元素

r - 基于一个列模态和其他列的新列

python - 如何用 Pandas 构建矢量化函数?

c - 通过在未初始化的数据段 (bss) 中打印 "garbage values",我们可以映射出

c# - 如何在控制台应用程序 .NET Core (C#) 中制作打开文件对话框?

c++ - std::bind() 不绑定(bind)参数

reactjs - 如何在 onSubmit 事件中使用 react-query useQuery?

string - 将两个不同列上第 n 次出现的 'foo' 和 'bar' 替换为相应列中所提供文