ahajib
ahajib

Reputation: 13510

Python: Convert 2D list to dictionary

I am trying to convert the following 2D list:

lst = [['A','B'],['C','D']]

To a dictionary like:

dict = {['A','B']:0, ['C','D']:1}

I have tried answers from other posts like the following:

{k: v for v, k in enumerate(lst)}

Which gives me this error:

unhashable type: 'list'

Any help is much appreciated. Thanks.

Upvotes: 0

Views: 1989

Answers (2)

tzaman
tzaman

Reputation: 47780

Lists are mutable, and thus cannot be used as dictionary keys. You could convert them to tuples if you want:

{tuple(k): v for v, k in enumerate(lst)}

Upvotes: 2

dnit13
dnit13

Reputation: 2496

Mutable types cannot be keys of a dictionary, but you can store tuples as dictionary keys for your purpose like this:

{tuple(k): v for v, k in enumerate(lst)}

Upvotes: 1

Related Questions