-3

I have a dictonary like -

d = {'a': [1, 2, 3], 'b': [4, 9], 'c': [1, 3, 9, 8]...}

I want to have a new dictonary which will be

r = {'a': 2, 'b': 6.5, 'c': 5.25}

which are average of list items. I want to do that in a dictonary comprehension code.

Anirban Nag 'tintinmj'
  • 5,572
  • 6
  • 39
  • 59
  • 1
    Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. Each of the steps is a trivial browser search: iterate over a dict, compute a mean, store the value in a new dict. – Prune Jun 23 '21 at 20:26
  • @Prune I got it. I was not able to picturise how to do the code. – Anirban Nag 'tintinmj' Jun 23 '21 at 21:13

1 Answers1

3
r = {
     k: sum(v) / len(v) 
     for (k, v) in d.items()
}
# {'a': 2.0, 'b': 6.5, 'c': 5.25}
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53