0

I want to create a dictionary in Python where the keys are lists.

The issue I want to face is that I have a list of multiple integer values (from 1 to 300), and depending different value-ranges, I want to convert those into characters. For example:

  • Values from 1 to 100 into character 'A'.
  • Values from 101 to 200 into character 'B'.
  • Values from 201 to 300 into character 'C'.

I tried this way but it didn't work:

dictionary = {[1, 100]:'A', [101, 200]:'B', [201, 300]:'C'}

But I get the error:

TypeError: unhashable type: 'list'

How could I do it?

jartymcfly
  • 1,945
  • 9
  • 30
  • 51

3 Answers3

3

Convert the lists to tuples. Tuples are hashable. Lists are not.

dictionary = {(1, 100):'A', (101, 200):'B', (201, 300):'C'}
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Thanks, it helped me a lot! But how can I check in which group is a value? I mean, if I have a value X, how could I search into the dictionary to check if it must be converted into 'A', 'B', or 'C'? – jartymcfly May 25 '17 at 14:00
  • @jartymcfly Sounds like you have a new question to ask. – khelwood May 25 '17 at 14:01
0

You can use a tuple, a JSON representation of the list, or a repr of the list:

>>> d1={repr([1, 100]):'A', repr([101, 200]):'B', repr([201, 300]):'C'}
>>> import json
>>> d2={json.dumps([1, 100]):'A', json.dumps([101, 200]):'B', json.dumps([201, 300]):'C'}
>>> d2
{'[101, 200]': 'B', '[1, 100]': 'A', '[201, 300]': 'C'}
>>> d1
{'[101, 200]': 'B', '[1, 100]': 'A', '[201, 300]': 'C'}
dawg
  • 98,345
  • 23
  • 131
  • 206
0

I don't know if I understood you correctly but you try to convert a list of ints in range [1, 300] to a list of characters with the characters A,B,C. Depending on the integer value. I don't see why you need a dict with keys of lists...

You can do it with a simple for loop and a few if statements.

import random

ints = [random.randint(1,300) for i in xrange(10)]

chars = []

for el in ints:
    if el > 0 and el <= 300:
        if el <= 100:
            chars.append("A")
        elif el <= 200:
            chars.append("B")
        else:
            chars.append("C")
    else:
        raise RuntimeError("element {} not in valid range.".format(el))

print(ints)
print(chars)

which returns

[23, 260, 276, 31, 170, 42, 16, 125, 102, 39]
['A', 'C', 'C', 'A', 'B', 'A', 'A', 'B', 'B', 'A']
2006pmach
  • 361
  • 1
  • 10