kate88
kate88

Reputation: 371

Getting values out of a python dictionary

I am struggling with python dictionaries. I created a dictionary that looks like:

d = {'0.500': ['18.4 0.5', '17.9 0.4', '16.9 0.4', '18.6 0.4'],
     '1.000': ['14.8 0.5', '14.9 0.5', '15.6 0.4', '15.9 0.3'],
     '0.000': ['23.2 0.5', '23.2 0.8', '23.2 0.7', '23.2 0.1']}

and I would like to end up having:

0.500 17.95 0.425 

which is the key, average of (18.4+17.9+16.9+18.6), average of (0.5+0.4+0.4+0.4)

(and the same for 1.000 and 0.000 with their corresponding averages)

Initially my dictionary had only two values, so I could rely on indexes:

for key in d:
    dvdl1 = d[key][0].split(" ")[0]
    dvdl2 = d[key][1].split(" ")[0]

    average = ((float(dvdl1)+float(dvdl2))/2)

but now I would like to have my code working for different dictionary lengths with lets say 4 (example above) or 5 or 6 values each...

Cheers!

Upvotes: 1

Views: 103

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

for k,v in d.iteritems():
    col1, col2 = zip(*[map(float,x.split()) for x in v])
    print k, sum(col1)/len(v), sum(col2)/len(v)
...     
0.500 17.95 0.425
1.000 15.3 0.425
0.000 23.2 0.525

How this works:

>>> v = ['18.4 0.5', '17.9 0.4', '16.9 0.4', '18.6 0.4']

first split each item at white-spaces and apply float to them, so we get a lists of lists:

>>> zipp = [map(float,x.split()) for x in v]
>>> zipp
[[18.4, 0.5], [17.9, 0.4], [16.9, 0.4], [18.6, 0.4]]    #list of rows

Now we can use zip with * which acts as un-zipping and we will get a list of columns.

>>> zip(*zipp)
[(18.4, 17.9, 16.9, 18.6), (0.5, 0.4, 0.4, 0.4)]

Upvotes: 5

Related Questions