1
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.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    What have you tried, and how does it fail? Please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Ezphares Sep 07 '19 at 10:36

2 Answers2

2
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]}
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45
1

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.

Sagar Gupta
  • 1,352
  • 1
  • 12
  • 26