trictionary?
Steven Bethard
steven.bethard at gmail.com
Sun Aug 28 19:21:10 EDT 2005
Randy Bush wrote:
> now i want to add a second count column, kinda like
>
> bin = {}
> for whatever:
> for [a, b] in foo:
> x = 42 - a
> if bin.has_key(x):
> bin[x.b] += 1
> else:
> bin[x.b] = 1
> bin[x.not b] = 0
> for x, y, z in bin.iteritems():
> print x, y, z
>
> should the dict value become a two element list, or is
> there a cleaner way to do this?
It would probably help if you explained what the real problem is you're
trying to solve. Using a two element list to store a pair of counts has
a bad code smell to me.
That said, you could write your code something like:
bin = {}
for whatever:
# NOTE: brackets are unnecessary
for a, b in foo:
x = 42 - a
# NOTE: 'in' is generally faster than has_key()
if x in bin
bin[x][0] += 1
else:
bin[x] = [1, 0]
# NOTE: extra parens necessary to unpack count list
for x, (y, z) in bin.iteritems():
print x, y, z
STeVe
More information about the Python-list
mailing list