dictionary with tuple keys

Paul Rubin no.email at nospam.invalid
Tue Dec 15 02:36:17 EST 2009


Brandon Devine <your.master at gmail.com> writes:
> I am probably not thinking straight anymore about this problem.  I
> have a dictionary with tuple keys in the format (a, b, A, B) and float
> values.  I want to collect all the keys with identical (a, b...),
> disregarding whatever (... A, B) might be.  Specifically, I want to
> sum the float values once I've collected these keys.  I am staring at
> my screen, pondering ugly things, and I just know I must be missing a
> Pythonic solution.  Any suggestions?

a,b are the first two elments of the tuple and d is the dict?  I.e. 
I think you want

    interesting_keys = [k for k in d.keys() if k[:2] == (a,b)]
    sum_of_values = sum(d[k] for k in interesting_keys)

You could write it a little differently to make fewer intermediate
results and so forth, but the above shows the idea.



More information about the Python-list mailing list