Search code examples
pythondictionary-comprehension

Dictonary comphrension of another dictonary to calcualte average of list values


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.


Solution

  • r = {
         k: sum(v) / len(v) 
         for (k, v) in d.items()
    }
    # {'a': 2.0, 'b': 6.5, 'c': 5.25}