0

I have an iteration process that after every iteration gives me a list, eg. a = [1,2,3,4]. Can I use this list as a key to a dictionary? The next iteration the same list changes elements, say after the 2nd iteration I have [2,1,3,4]. Can I construct a dictionary d = {[1,2,3,4]:"value1", [2,1,3,4]:"value2"]}

I tried doing it but python tells me I can't do it using a list. So I tried with a tuple but I can't get it to work.

trylist = (1,2,3,4)   
dictionary = {}
d[trylist] = 'value'
print(dictionary)

Expected result would be: d = {[1,2,3,4]:"value1", [2,1,3,4]:"value2"]}

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
immalee
  • 43
  • 7
  • 1
    No, dictionary keys cannot be lists. In your code, use `dictionary[trylist] = 'value'`. – Austin Jan 21 '19 at 15:20
  • thank you very much, I will try it. – immalee Jan 21 '19 at 15:30
  • 1
    When you do `dictionary = {}`, `dictionary` is your dictionary. `d` is not defined in your code. We need to add to dictionary `dictionary` created on line above it, not `d`. – Austin Jan 21 '19 at 15:33
  • I undestand that now, thank you. I'm only a beginner and sometimes i don't notice things :( I hope this changes. Again thank you! – immalee Jan 21 '19 at 15:37

1 Answers1

0

not sure if this works for you but you could just convert the list to a string, so that you can use it as a key in the dictionary:

trylist = [1,2,3,4]
d = {}
d[str(trylist)] = 'value'
print(d)

but using a tuple should work too:

trylist = (1,2,3,4)
d = {}
d[trylist] = 'value'
print(d)
flashback
  • 383
  • 3
  • 6
  • thank you i will try it and see if this works too. I wonder if the same applies if I don't have numbers inside my list, but strings for example. I will check it out thank you. – immalee Jan 21 '19 at 15:31