[Tutor] list objects are unhashable

Martin Walsh mwalsh at groktech.org
Tue Jul 1 05:52:10 CEST 2008

Hi Norman,

Norman Khine wrote:
>         for brain in brains:
>             x = getattr(brain, horizontal)
>             x = string.join(x, '' )
>             y = getattr(brain, vertical)
>             y = string.join(y, '' )
>             if x and y and (x, y) in table:
>                 table[(x, y)] += 1
>                 table[(x, '')] += 1
>                 table[('', y)] += 1
>                 table[('', '')] += 1

For what it's worth, string.join has been deprecated since the addition
of the join method for str and unicode types. Other deprecated string
module functions are documented here: http://docs.python.org/lib/node42.html

If I'm not mistaken, the conventional form would be:

  x = ''.join(x)

> So now my list becomes a string, which is not really good for me, as
> this fails when there is more then one item.
> Is there a better way to loop through this and sum up all occurrences of
> each entry ie  'airport-car-parking'

Maybe, can you show us a brief excerpt of what 'table' might look like
before the loop, and what you expect it to look like after one
iteration, with data samples for both x and y?

Most likely it's just me, but I'm having trouble reconciling your code
examples with your questions. AFAICT, either you want more than just a
simple count of occurrences from your data set, or you have some
confusion regarding dictionaries (if 'table' is a dictionary, of course).

If you want a count of each unique occurrence in a list -- not sure if
it's better, but something like this might get you started (untested):

from sets import Set
x = ['airlines-scheduled', 'airport-car-parking',
     'more-than-100ml', 'do-not-bring-toothpaste',
     'airport-car-parking', 'airlines-scheduled']

entity_count = dict((item, x.count(item)) for item in Set(x))
print entity_count['airlines-scheduled']
# 2


More information about the Tutor mailing list