Python: How to access tuple values inside a dictionary of a dictionary
python
Solution
You can do it like this:
r_vals = [u['item3'].r for u in mydict.itervalues() if 'item3' in u]
if r_vals:
r_avg = sum(r_vals)/len(r_vals)
else:
r_avg = 0 # ???
Problem
I have a dict of dict setup as follows: ``` from collections import namedtuple Point = namedtuple('Point', 'r w') mydict= { 'user1': {'item1': Point(2.5,0.1),'item2': Point(3.5,0.6)}, 'user2': {'item1': Point(3.0,0.3), 'item3': Point(3.5,0.8)}, 'user3': {'item1': Point(2.0,0.4),'item3': Point(0.5,0.1), 'item4': Point(1.5,0.7)} } ``` I would like to find an efficient way of getting the average of the values in Point. i.e. I want to get the average of the r point value (point.r) for 'item3' which is (3.5+0.5)/2 Thanks,