[Tutor] list objects are unhashable

Norman Khine norman at khine.net
Mon Jun 30 20:55:36 CEST 2008


Hello,

I would like to count list items but am not 100% sure how to do it.

Here is what I have so far:

         for brain in brains:
             x = getattr(brain, horizontal)
             y = getattr(brain, vertical)
             if x and y and (x, y) in table:
                 table[(x, y)] += 1
                 table[(x, '')] += 1
                 table[('', y)] += 1
                 table[('', '')] += 1

but when I run this, I get the following error on the line:

if x and y and (x, y) in table:

TypeError: list objects are unhashable

where:

x = ['airlines-scheduled', 'airport-car-parking']


I am basically looping through files within each file, I have an entity, 
for example:

file1
<topic>airlines-scheduled airport-car-parking</topic>

file2
<topic>airport-car-parking</topic>

etc...

So the above code counts all occurrences of  'airport-car-parking' and 
sums it up.

All works well if, I change the code to:

         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

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'

Cheers

Norman




More information about the Tutor mailing list