I have the following dictionary for which I’d like to produce a new dictionary that gives the original keys but the values are computed using len, min and sum.
scores = {
"Monday" : [21, 23, 24, 19],
"Tuesday" : [16, 15, 12, 19],
"Wednesday" : [23, 22, 23],
"Thursday": [ 18, 20, 26, 24],
"Friday": [17, 22],
"Saturday" : [22, 24],
"Sunday" : [21, 21, 28, 25]
}
I initially tried to use the following but it only returns a single value:
for k, v in scores.items():
stat = {
k : [len(v), min(v), sum(v)]
}
This returns: {'Sunday': [4, 21, 95]}
Doing some research, I managed to use the following comprehension to achieve the outcome:
stats = {k : [len(v), min(v), sum(v)] for k, v in scores.items()}
This returns:
{'Monday': [4, 19, 87], 'Tuesday': [4, 12, 62], 'Wednesday': [3, 22, 68], 'Thursday': [4, 18, 88], 'Friday': [2, 17, 39], 'Saturday': [2, 22, 46], 'Sunday': [4, 21, 95]}
I would really like to understand why my first attempt only produced a single value and didn’t iterate through the entire dictionary?
I’m new to learning Python so very keen to understand the difference in methods and what I was doing incorrect with the first method.
Many thanks! JJ
CodePudding user response:
This code:
for k, v in scores.items():
stat = {
k : [len(v), min(v), sum(v)]
}
is the equivalent of doing:
stat = {"Monday" : [len(scores["Monday"]), min(scores["Monday"]), sum(scores["Monday"])}
stat = {"Tuesday" : [len(scores["Tuesday"]), min(scores["Tuesday"]), sum(scores["Tuesday"])}
...
stat = {"Sunday" : [len(scores["Sunday"]), min(scores["Sunday"]), sum(scores["Sunday"])}
On each iteration of the loop, you're re-assigning stat
to a new single-item dictionary. The last one is Sunday
, so that's the final value that stat
has after the loop is finished.
If you did something like:
stat = {}
for k, v in scores.items():
stat[k] = [len(v), min(v), sum(v)]
your end result would be an accumulation of all the values, similar to the result you get from the dictionary comprehension (which is generally the preferred way of building a dictionary through iteration).
CodePudding user response:
your script is iterating arround all dictionary
but you are overriting the result dictionary
try something like:
stats = []
for k, v in scores.items():
stat = {
k : [len(v), min(v), sum(v)]
}
stats.append(stat)
print(stats)