检索满足某些条件的字典



我有一个如下所示的字典:

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,

},
],
}

我想获得上述数据模式的Test分数和考试分数,其中有一个嵌套字典,键为'tag',键为' id ';, ' height ';和"age">

所以期望值应该是"Test Score"=20.0和"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

你只需要迭代"Student"索引的列表:

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,

},
],
}
search_tag = ["id", "height", "age"]
val_list = []
for item in x["Student"]:
if all(t in search_tag for t in item['tags']):
val_list.append(item["Test Score"])
val_list.append(item["Exam Score"])
print(val_list)

输出:

[20.0, 80.0]
x = {'Student': [{'Exam Score': 70.0,
'Nationality': '',
'Test Score': 10.0,
'tags': {'class': 'Biology', 'gender': 'male', 'name': 'Alex'}},
{'Exam Score': 80.0,
'Nationality': '',
'Test Score': 20.0,
'tags': {'age': '15', 'height': '170', 'id': 'A123'}}]}
search_tag = {"age", "height", "id"}
for student in x["Student"]:
if search_tag.issubset(student["tags"]):
print([student["Test Score"], student["Exam Score"]])

使用一个集合来检查条件。

这个打印

[20.0, 80.0]

相关内容

  • 没有找到相关文章

最新更新