简体   繁体   中英

How do I make a list a key value in a dictionary?

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!

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})

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.

([1,2]:0, [2,3]:0) is not a dictionary. I think you meant to use: {(1,2):0, (2,3):1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM