我有一个字典,如下所示:
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/