I'm trying to produce a python dictionary that results in the following:
{'student_1': [{2017: 3}, {2018: 4}], 'student_2': [{2017: 60}, {2021: 153}], 'student_3': [{2015: 45}]}
The data comes from a database table that is tabular and looks like this:
| yearfiled | count | name |
| 2017 | 3 | student_1 |
| 2018 | 4 | student_1 |
| 2017 | 60 | student_2 |
| 2021 | 153 | student_2 |
| 2015 | 45 | student_3 |
I can produce the desired formatted dictionary, however, each key in the dictionary is getting the values replaced with the last key's values in the database table.
# chartdata is a fetchall() from a executed database query
q={}
for a,b,c in chartdata:
v=[]
q[a]=b
v.append(q)
datasetnew[c] = v
# Results
{'student_1': [{2015: 45}], 'student_2': [{2015:45}], 'student_3': [{2015:45}]}
I'm a bit perplexed on how to solve this. Any thoughts?
I tried a few different lines of code, however, none produced the correct results.
For example, this change put ALL the values for each student in every students key.
v=[]
q={}
for a,b,c in chartdata:
q[a]=b
v.append(q)
datasetnew[c] = v
CodePudding user response:
You can achieve this more easily with defaultdict
:
from collections import defaultdict
datasetnew = defaultdict(list)
for year, count, name in chartdata:
datasetnew[name].append({ year: count })
Result is:
{
'student_1': [{2017: 3}, {2018: 4}],
'student_2': [{2017: 60}, {2021: 153}],
'student_3': [{2015: 45}]
}
However, I wonder why you would create lists of dictionaries that each only have one key? It would seem more useful to combine those little dictionaries into one dictionary per student:
datasetnew = defaultdict(dict)
for year, count, name in chartdata:
datasetnew[name][year] = count
This produces this structure:
{
'student_1': {2017: 3, 2018: 4},
'student_2': {2017: 60, 2021: 153},
'student_3': {2015: 45}
}