Reputation: 13
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!
Upvotes: 0
Views: 103
Reputation: 33407
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})
Upvotes: 4
Reputation: 3454
([1,2]:0, [2,3]:0)
is not a dictionary. I think you meant to use: {(1,2):0, (2,3):1}
Upvotes: 0
Reputation: 309959
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.
Upvotes: 3