newbie dictionary question

Raymond Hettinger python at rcn.com
Sun Apr 21 20:54:12 EDT 2002


"James Chapman ude.awoiu at nampahc-semaj>" <<reverse> > Hi,
>
> I'd preferably like to use something like this but my problem is precisely
> this. I have for example to dictionaries as follows:
>
> a= {4.95:100,4.97:90,4.99:95}
> b={4.95:100,4.96:99}
>
> and I would wonder if there is an elegent way to do something like:
>
> c = a+b
> c={4.95:200,4.96:99,4.97:90,4.99:95}

I'm not sure if this counts as elegant, but it works:
>>> [a.__setitem__(k, a.get(k,0)+v) for k,v in b.iteritems()]
[None, None]
>>> a
{4.9699999999999998: 90, 4.9500000000000002: 200, 4.9900000000000002: 95,
4.96: 99}

FWIW, I think using floats as a key is perilous.


Raymond Hettinger





More information about the Python-list mailing list