trictionary?
Adam Tomjack
adamtj at adamtj.org
Sun Aug 28 18:49:30 EDT 2005
Randy,
I'd probably use a two element list.
Instead of using an if/else to check if an element is in your dict and
initialize it, you can use the setdefault() function. The docs for
dictionaries explain it pretty well.
bin = {}
for whatever:
for [a, b] in foo:
x = 42 - a
bin_item = bin.setdefault(x, [1, 0])
bin_item[0] += 1
for x, (y, z) in bin.iteritems():
print x, y, z
You could also use a class like a C-style struct if you want named items:
class BinItem:
def __init__(self, s=0, t=0):
self.s = s
self.t = t
bin = {}
for a, b in foo:
x = 42 - a
bin_item = bin.setdefault(x, BinItem(1, 0))
bin_item.s += 1
for x, item in bin.iteritems():
print x, item.s, item.t
Luck in battle,
Adam
Randy Bush wrote:
> i have some code which looks kinda like
>
> bin = {}
> for whatever:
> for [a, b] in foo:
> x = 42 - a
> y = 42 - b
> if bin.has_key(x):
> bin[x] += 1
> else:
> bin[x] = 1
> for i, j in bin.iteritems():
> print i, j
>
> 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?
>
> randy
>
More information about the Python-list
mailing list