jescilinn
jescilinn

Reputation: 3

Convert the tuples in a list to a dictionary and calculate the frequency

Three friends – Mike, John, and Tom – measured their jumps lengths in centimeters. We've stored their jump results in the template code. Create a dictionary named avg_results which will store the names as keys and their average jump lengths as values.

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

I only know how to calculate the sum of measure for each of them, but I don't know how to iterate and get the count of each of them.

for jump in jumps:
  name,length=jump
  dict_results[name]=dict_results.get(name,0)+length

Upvotes: 0

Views: 114

Answers (4)

Sheldore
Sheldore

Reputation: 39052

Following is one possible solution using Dictionary based on this answer

dct = {}

for i, j in jumps:
    group = dct.get(i, [])
    group.append(j)
    dct[i] = group

avg_results = {k:sum(v)/len(v) for k, v in dct.items()}
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

dict_results = {}
jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]
for jump in jumps:
    name, length = jump
    if name in dict_results:
        dict_results[name].append(length)
    else:
        dict_results[name] = [length]

for key, val in dict_results.items():
    dict_results[key] = sum(val) / len(val)

print(dict_results)

Output

{'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

Upvotes: 1

RoadRunner
RoadRunner

Reputation: 26315

Have you tried grouping with a collections.defaultdict(list), then taking the average from dividing sum() by len():

from collections import defaultdict

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

d = defaultdict(list)
for name, length in jumps:
    d[name].append(length)

avg = {k: sum(v) / len(v) for k, v in d.items()}

print(avg)
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

You can also use statistics.mean() to get the average:

from statistics import mean

avg = {k: mean(v) for k, v in d.items()}

print(avg)
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

Upvotes: 1

Olvin Roght
Olvin Roght

Reputation: 7812

Code:

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

res = {}
for name, length in jumps:
    res[name] = [length] if name not in res else res[name] + [length]
avg_results = {k: sum(v) / len(v) for k, v in res.items()}

Output:

{'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

Upvotes: 2

Related Questions