Question

I have a dictionary:

d = {'0.766': [('8.0', '-58.47'), ('192.0', '-83.41')], '0.094': [('26.0', '112.01'), ('46.0', '110.19')], '0.313': [('14.0', '75.52'), ('48.0', '77.07')]}

And I would like to add the corresponding values in the tuple, so the output looks like that:

key, sum of 1st values in tuple, sum of 2nd values in tuple
0.766, 200.0, -141.88
0.094, 72.0, 222.20
...

Is there a simple way to do that? So far I found sum(d.values()), but it does not do exactly what I would like to...

Cheers, Kate

PS. Now I am also wondering how to get the output such as:

key, sum of 1st values in tuple, DIFFERENCE of 2nd values in tuple
0.766, 200.0, 24.94
0.094, 72.0, 1.82
...

when I want to perform two different operation...

Thank you!

Was it helpful?

Solution

print [(k,) + tuple(sum(map(float, item)) for item in zip(*d[k])) for k in d]
# [('0.766', 200.0, -141.88),
#  ('0.313', 62.0, 152.58999999999997),
#  ('0.094', 72.0, 222.2)]

What we have above is called a list comprehension. It actually works similar to this, but in an efficient way

result = []
for k in d:
    temp = tuple()
    for item in zip(*d[k]):
        temp += (sum(map(float, item)),)
    result.append((k,) + temp)
print result

To handle the case you mentioned in the edited question, you can do something like this

result = []
for k in d:
    temp = tuple()
    fir, sec = zip(*d[k])
    fir, sec = sum(map(float, fir)), reduce(lambda i,j: float(i)-float(j), sec)
    result.append((k,) + (fir, sec))
print result

OTHER TIPS

I think this answer might be a little bit more intuitive. It does not use "*" which is confusing to me:

print "\n".join(
    [
        "%s, %s, %s" % 
        (
            i, 
            sum([float(j[0]) for j in d[i]]), 
            sum([float(j[1]) for j in d[i]]),
        ) 
        for i in d.keys()
    ]
)

The follow-up question you had will require to actually write loops because you are not simply adding (or performing a similar cumulative operation) a list of numbers. Instead you are subtracting the second number from the first. Since order is important, list comprehension as I have shown above won't work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top