Counting number of each item in a list.

per9000 per9000 at gmail.com
Mon Mar 20 07:03:39 EST 2006


Dear counters,

I have also encountered the above problem, and I frequently use the two
blocks of code below.

The first one is commented already - except that this version does not
start from an empty dict.

The second "inverts" the first one. Meaning that a dict in word2hits
style:

my_dict['the'] = 120
my_dict['word'] = 4
...
my_dict['gene'] = 4

becomes a dict in hits2words style:

new_dict[4] = ['word','gene', ...]
new_dict[120] = ['the', ...]

I used these to count genes in in abstracts from pubmed the when I
"invented" them (but it took some time to remove them from the code and
use them as functions).

def dict_add(indict,inlist,init=1):
  for item in inlist:
    if indict.has_key(item):
      indict[item] += 1
    else:
      indict[item] = init
  return indict
# end def

def dict_invert(indict):
  new_dict = {}
  for key in indict.keys():
    if new_dict.has_key(indict[key]):
      new_dict[indict[key]].append(key)
    else:
      new_dict[indict[key]] = [key]
  return new_dict
#end def

A good idea could be to change the header of the first one (if you want
the option to start counting from zero) into:
def dict_add(inlist,indict={},init=1):

/P9K




More information about the Python-list mailing list