[Tutor] counting occurrences of pairings

Jeff Shannon jeff@ccvcorp.com
Wed, 24 Apr 2002 17:45:57 -0700


> Israel Evans <israel@lith.com> wrote:
>
> I found that I had to create the spaces before I started assigning values to
> them in a different way than I was.

There's a nice feature of dicts that you might want to take advantage of...

Instead of initializing your dictionaries with 0 for each pair of numbers that you
expect, you can use the dictionary's get() method.  This will return the value for a
key if it exists, or a default value if it doesn't exist.

>>> d = {'one':1, 'two':2}
>>> d.get('one', 0)
1
>>> d.get('two', 0)
2
>>> d.get('three', 0)
0
>>> d.get('three', 3)
3
>>>

Thus, the simple way to count, using dictionaries, is this:

    d[key] = d.get(key, 0) + 1

This will add one to whatever preexisting value d[key] had, or create a new key with
the value of one if it didn't exist previously.

Another trick you might want to use -- instead of using nested dictionaries, like
you do, you could instead use a single dictionary, and have the key be an (x, y)
tuple instead of a string.

If we combine these two tricks, then your code will end up looking something like
this:


>>> atupe = ('a', 'b', 'c', 'd', 'e')
>>> btupe = ('a', 'f', 'g', 'd', 'h')
>>> ctupe = ('a', 'i', 'j', 'f', 'd')
>>> alltupe = (atupe, btupe, ctupe)
>>> alldict = {}
>>> for tupe in alltupe:
...  for char in tupe:
...   for other in tupe:
...    alldict[(char,other)] = alldict.get((char,other), 0) + 1
...
>>> for key, value in alldict.items():
...  print key, '--', value
...
('a', 'd') -- 3
('a', 'e') -- 1
('c', 'c') -- 1
('c', 'a') -- 1
('a', 'a') -- 3
('a', 'b') -- 1
< ......  >  # ommitting numerous lines of output
('d', 'f') -- 2
('b', 'c') -- 1
('b', 'b') -- 1
>>>

Hope that helps!

Jeff Shannon
Technician/Programmer
Credit International