# trictionary?

Randy Bush randy at psg.com
Mon Aug 29 05:17:58 CEST 2005

```>>     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.

actually, that code fragment was meant to do that.  it's pretty much
what i needed to do at that point, just the variable names made
simple.

> Using a two element list to store a pair of counts has a bad code
> smell to me.

exactly.  which is why i was asking.

> 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

so, to do this using the real names, it looks like

for [start, end, AS, full] in heard:
week = int((start-startDate)/aWeek)
if week in bin:
if full:
bin[week][0] += 1
else:
bin[week][1] += 1
else:
if full:
bin[week] = [1, 0]
else:
bin[week] = [0, 1]
...
for i, (j, k) in bin.iteritems():
if j == 0:
print str(i) + ",," + str(k)
elif k == 0:
print str(i) + "," + str(j)
else:
print str(i) + "," + str(j) + "," + str(k)

which is still pretty darned grotty and unexpressive.  of course,
i could be a bit more obscure and do

if week in bin:
bin[week][not full] += 1
else:
bin[week] = [ full, not full ]

except i probably have to coerce the types or something.  less
code but less obvious.

randy

```