Chirantan Saha
Chirantan Saha

Reputation: 11

How to create a special dictionary with multiple values under one key?

school = [['dia', 87], ['ria', 100], ['gud', 59], ['ria', 85], ['gud', 76], ['don', 99]]

This array contains the students and their marks (yes, there are some duplicate students who are having diff values).

I want to convert it into this dictionary to find the avg score:

school_dict = { dia:[87], ria:[100,85], gud:[59,76], don:[99] }

Let me know if anyone can solve this for me.

Upvotes: 1

Views: 41

Answers (2)

Sagar Gupta
Sagar Gupta

Reputation: 1450

From a performance point of view, defaultdict is faster than dict.setdefault(), so you may use that too:

from collections import defaultdict
school = [['dia', 87], ['ria', 100], ['gud', 59], ['ria', 85], ['gud', 76], ['don', 99]]
d = defaultdict(list)
for s in school:
    d[s[0]].append(s[1])
print(dict(d))

Output:

{'dia': [87], 'ria': [100, 85], 'gud': [59, 76], 'don': [99]}

Follow this: setdefault vs defaultdict performance for performance-related discussion.

Upvotes: 1

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4199

res = {}
for x in school:
    res.setdefault(x[0],[]).append(x[1])
print(res)      

Output

{'dia': [87], 'ria': [100, 85], 'gud': [59, 76], 'don': [99]}

Upvotes: 2

Related Questions