简体   繁体   中英

Python use list of list as key in dict

I have a list of lists like this:

l = [[1,2], [3,4], [5,6]]

How can I use l as a key in a dict? I tried to make a frozenset out of l :

l = frozenset(l)
d[l] = True

but I'm getting

TypeError: unhashable type: 'list'

TypeError: unhashable type: 'list'

This is because you still have the inner lists which are unhashable.

You can do:

>>> key = frozenset(map(frozenset, l))
>>> {key: 'test'}
{frozenset([frozenset([5, 6]), frozenset([1, 2]), frozenset([3, 4])]): 'test'}

Or, make it a tuple :

>>> key = tuple(map(tuple, l))
>>> {key: 'test'}
{((1, 2), (3, 4), (5, 6)): 'test'}

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