dictionary with tuple keys

Chris Rebert clp2 at rebertia.com
Tue Dec 15 00:59:35 EST 2009


On Mon, Dec 14, 2009 at 9:49 PM, Brandon Devine <your.master at gmail.com> wrote:
> Hi all,
>
> 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?

from collections import defaultdict

new_dict = defaultdict(int)
for tupkey in your_dict:
    new_key = tupkey[:2]
    new_dict[new_key] += your_dict[tupkey]

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list