dict indexed by lists - ?

Steven Bethard steven.bethard at gmail.com
Thu Feb 3 19:42:21 EST 2005


Alexander Zatvornitskiy wrote:
> Hello All!
> 
> I'am trying to make something like this:
> 
> CPT={ ['b0','c0']:1, ['b0','c1']:0, ['b1','c0']:3, ['b1','c1']:1 }
> 
> but python says "TypeError: list objects are unhashable"
> 
> I can replace list with touple: CPT={ ('b0','c0'):1, ('b0','c1'):0, ...and so
> on. But, where is one problem: indexes (or, more precisely, keys) are generated
> dynamically, like code below! I can't do it with touples.
> 
> 
>     key=[]
>     for up in uplinks:
>       key.append(up.state(0))
> 
> 
> and, later, modifying it like this:
>   key[2]=up.next_state()
>   ...
>   print CPT[key]
> 
> Any suggestions?

You can manually add the tuple calls:

     CPT = {('b0','c0'):1, ('b0','c1'):0, ('b1','c0'):3, ('b1','c1'):1}
     ...
     key = [up.state(0) for up in uplinks]
     ...
     key[2] = up.next_state()
     ...
     print CPT[tuple(key)]

I've only added the tuple call when you actually access CPT, but 
depending on your code, you might find that you can make the tuple call 
earlier.  For example, the following code should work:

     CPT={('b0','c0'):1, ('b0','c1'):0, ('b1','c0'):3, ('b1','c1'):1}
     ...
     key = tuple([up.state(0) for up in uplinks])
     ...
     print CPT[key]

where basically you convert key back to a tuple any time it's changed.

STeVe



More information about the Python-list mailing list