2

I want to put lists inside a dictionary. I want do like this:

trail = {[]}

for i in states:
    for j in states:
        if(max_val < temp_V[j][i]):
            max_val = temp_V[j][i]
            trail[i].append(j)

But I am getting an error at trail = {[]}. I'm new to Python. How can I do this?

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
Darshana
  • 2,462
  • 6
  • 28
  • 54

1 Answers1

4

Use defaultdict

from collections import defaultdict
trail = defaultdict(list)

It will construct an empty list for any key when you try to access it for the first time so

trail[i].append(j)

will work as expectd. As for:

trail = {[]}

You need to have a keys and corresponding values for a valid dictionary literal eg.

{'a': 1, 'b': 2}

{[]} trys to makes a set instead eg.

>>> {1}
set([1])

but sets only support hashable items, see hash table, and a list (which can be modified) is therefore not hashable.

jamylak
  • 128,818
  • 30
  • 231
  • 230