Dictionary question.

Brian van den Broek bvande at po-box.mcgill.ca
Thu Apr 21 20:58:37 EDT 2005


hawkesed said unto the world upon 2005-04-21 20:28:
> Actually,
>   I think I got it now. Here is what I did:
> 
>>>>for num in alist:
> 
> ... 	if adict.has_key(num):
> ... 		x = adict.get(num)
> ... 		x = x + 1
> ... 		adict.update({num:x})
> ... 	else:
> ... 		adict.update({num:1})
> ...
> 
>>>>adict
> 
> {128: 2, 129: 2, 132: 1, 153: 1, 30: 1, 53: 1, 57: 1, 61: 1, 66: 2, 67:
> 1, 69: 2, 71: 1, 72: 1, 73: 2, 74: 1, 75: 2, 76: 2, 77: 2, 78: 2, 82:
> 1, 84: 1, 85: 4, 87: 2, 88: 3, 89: 1, 91: 1, 92: 1, 93: 2, 94: 2, 95:
> 3, 96: 1, 97: 3, 98: 2, 99: 1, 100: 6, 101: 4, 102: 2, 103: 1, 104: 1,
> 105: 1, 106: 2, 107: 2, 108: 2, 109: 2, 111: 3, 112: 1, 114: 3, 115: 3,
> 116: 3, 118: 1, 119: 2, 122: 2, 123: 1, 125: 1, 126: 1}
> Thanks all for the help and best regards!
> Ed
> 


Hi Ed,

I think there is a more Pythonic way. Here's something I used in a 
similar context:

def get_frequency_dict(sequence):
     '''sequence of hashables -> dictionary of frequency of members

     Given a sequence of items, each of which is hashable (i.e. can
     serve as a key in a dictionary), the function returns a
     dictionary, using the items as keys, and the number of their
     occurrences as values.

     Usage:
     >>> get_frequency_dict([1,2,2,3,3,3,4,4,4,4])
     {1: 1, 2: 2, 3: 3, 4: 4}
     >>> get_frequency_dict([[], "will fail as list aren't hashable"])
     ...
     TypeError: list objects are unhashable
     '''
     frequency_dict = {}

     for element in sequence:
         frequency_dict[element] = frequency_dict.setdefault(
                                     element, 0) + 1

     return frequency_dict

HTH,

Brian vdB





More information about the Python-list mailing list