I need to make a dictionary where you can reference [[1,2],[3,4]] --> ([1,2]:0, [2,3]:0) I've tried different ways but I can't use a list in a dictionary. So i tried using tuples, but its still the same. Any help is appreciated!
3 Answers 3
You need to use tuples:
dict.fromkeys((tuple(i) for i in [[1,2],[3,4]]), 0)
or (for python2.7+)
{tuple(i): 0 for i in [[1,2], [3,4]]}
Edit:
Reading the comments, OP probably want to count occurrences of a list:
>>> collections.Counter(tuple(i) for i in [[1,2], [1,2], [3,4]])
Counter({(1, 2): 2, (3, 4): 1})
19 Comments
1 as the last argument instead of 0collections.Counterdict((tuple(i),0) for i in [[1,2],[3,4]]) rather than using the classmethod -- But that's just a matter of taste I suppose. (It's also closer to the syntax used to create the dict-comp in py2.7)Lists can't be used as dictionary keys since they aren't hashable (probably because they can be mutated so coming up with a reasonable hash function is impossible). tuple however poses no problem:
d = {(1,2):0, (3,4):0}
Note that in your example, you seem to imply that you're trying to build a dictionary like this:
((1,2):0, (3,4):0)
That won't work. You need curly brackets to make a dictionary.
Comments
([1,2]:0, [2,3]:0) is not a dictionary. I think you meant to use: {(1,2):0, (2,3):1}
id()builtin function on your list and use the result of that as your key. These are two very different use cases and you haven't given enough information for us to determine which approach solves your problem.