Question

I have a defaultdict that has multiple values per key. I want to calculate the average value for each key. I can't figure out how to access the values associated with each key. Can anyone help?

[('T.Max', [1.62, 1.65, 1.62], ('T.Spon', [0.30, 0.34, 0.34])]
Was it helpful?

Solution

.items(), .viewitems(), and .iteritems() work just like for dictionaries (and indeed, it seems like you printed out the value of .items()). They give you a list/view/iterator over key-value pairs. For example, using a dictionary comprehension to get the mean value for each key:

>>> {k: sum(vals) / len(vals) for k, vals in the_defaultdict.viewitems()}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top