首页 > 解决方案 > 检索满足某些条件的字典

问题描述

我有一本字典,如下所示:

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"]) 

标签: pythonlistdictionarydata-science

解决方案


您可以将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

推荐阅读