Let's say I have this variable list_1 which is a list of dictionaries. Each dictionary has a nested dictionary called "group" in which it has some information including "name".
What I'm trying to do is to sum the scores of each unique group name.
So I am looking for an output similar to:
Total Scores in (Ceramics) = (18)
Total Scores in (Math) = (20)
Total Scores in (History) = (5)
I have the above info in parenthesis because I would like this code to work regardless of the amount of items in the list, or amount of unique groups represented.
The list_1 variable:
list_1 = [
{"title" : "Painting",
"score" : 8,
"group" : {"name" : "Ceramics",
"id" : 391}
},
{"title" : "Exam 1",
"score" : 10,
"group" : {"name" : "Math",
"id" : 554}
},
{"title" : "Clay Model",
"score" : 10,
"group" : {"name" : "Ceramics",
"id" : 391}
},
{"title" : "Homework 3",
"score" : 10,
"group" : {"name" : "Math",
"id" : 554}
},
{"title" : "Report 1",
"score" : 5,
"group" : {"name" : "History",
"id" : 209}
},
]
My first idea was to create a new list variable and append each unique group name. Here's the code for that. But will this help in ultimately finding the sum of the scores for each one of these?
group_names_list = []
for item in list_1:
group_name = item["group"]["name"]
if group_name not in group_names_list:
group_names_list.append(group_name)
This gives me the value of group_names_list as:
['Ceramics','Math','History']
Any help or suggestions are appreciated! Thanks.
We can use the dict. fromkeys method of the dict class to get unique values from a Python list. This method preserves the original order of the elements and keeps only the first element from the duplicates.
It is pretty easy to get the sum of values of a python dictionary. You can first get the values in a list using the dict. values(). Then you can call the sum method to get the sum of these values.
USE sum() TO SUM THE VALUES IN A DICTIONARY. Call dict. values() to return the values of a dictionary dict. Use sum(values) to return the sum of the values from the previous step.
The simplest way to count unique values in a Python list is to convert the list to a set considering that all the elements of a set are unique. You can also count unique values in a list using a dictionary, the collections. Counter class, Numpy. unique() or Pandas.
You can use a dict to keep track of scores per name:
score_dict = dict()
for d in list_1:
name = d['group']['name']
if name in score_dict:
score_dict[name] += d['score']
else:
score_dict[name] = d['score']
print(score_dict)
RESULTS: {'Ceramics': 18, 'Math': 20, 'History': 5}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With