Reputation: 33
I need to filter this data by the month. I need the results to a be a list of lists like lst = [[92], [86], [89]]
This is what I have tried:
data_dict = [
{
"student": "john",
"subject": "english",
"grade": "A",
"marks": 92,
"assessement type": "exam",
"date": [2, 1, 2021],
},
{
"student": "john",
"subject": "math",
"grade": "B",
"marks": 86,
"assessement type": "essay",
"date": [2, 3, 2021],
},
{
"student": "john",
"subject": "history",
"grade": "B",
"marks": 89,
"assessement type": "presentation",
"date": [22, 2, 2021],
},
]
lst = []
for x in data_dict:
for i in range(1, 13):
if x["date"][1] == i:
lst.append(x["marks"])
output:
lst = [92, 86, 89]
How do I make the results a list of lists?
ETA. I need to learn how to do these things without an external library ready for exams in a few weeks.
Upvotes: 0
Views: 52
Reputation: 19
lst = []
for i in range(1,13):
templst = []
for x in data_dict:
if x["date"][1]==i:
templst.append(x["marks"])
lst.append(templst)
lst
out: [[92, 93, 89], [89], [86], [], [], [], [], [], [], [], [], []]
Upvotes: 0
Reputation: 168976
You'll probably have a better time gathering the grades up into a dict per month, and then if you need a list of lists with all months, no matter if they have grades, that's easy enough:
from collections import defaultdict
data_dict = [
{
"student": "john",
"subject": "english",
"grade": "A",
"marks": 92,
"assessement type": "exam",
"date": [2, 1, 2021],
},
{
"student": "john",
"subject": "math",
"grade": "B",
"marks": 86,
"assessement type": "essay",
"date": [2, 3, 2021],
},
{
"student": "john",
"subject": "history",
"grade": "B",
"marks": 89,
"assessement type": "presentation",
"date": [22, 2, 2021],
},
]
grades_by_month = defaultdict(list)
for x in data_dict:
grades_by_month[x["date"][1]].append(x["marks"])
grades_every_month = [grades_by_month[x] for x in range(1, 13)]
print(grades_every_month)
prints out
[[92], [89], [86], [], [], [], [], [], [], [], [], []
(grades_by_month
will look like {1: [92], 3: [86], 2: [89]}
.)
Upvotes: 1