dict indexed by lists - ?

  • Thread starter Alexander Zatvornitskiy
  • Start date
A

Alexander Zatvornitskiy

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?


Alexander, (e-mail address removed)
 
S

Steven Bethard

Alexander said:
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
 
A

Alexander Zatvornitskiy

ðÒÉ×ÅÔ All!

04 ÆÅ×ÒÁÌÑ 2005 × 02:47, Alexander Zatvornitskiy × Ó×ÏÅÍ ÐÉÓØÍÅ Ë All ÐÉÓÁÌ:
AZ> I'am trying to make something like this:
AZ> CPT={ ['b0','c0']:1, ['b0','c1']:0, ['b1','c0']:3, ['b1','c1']:1 }

Thanks, I fix it - i use lists.

AZ> and, later, modifying it like this:
AZ> key[2]=up.next_state()

replaced with:
k=k[:cur_idx-1]+up.next_state()+k[cur_id+1:]

AZ> ...
AZ> print CPT[key]

AZ> Any suggestions?


AZ> Alexander, (e-mail address removed)


Alexander, (e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,609
Members
45,253
Latest member
BlytheFant

Latest Threads

Top