-1

How can I zip list of list into dictionary in Python?

Example

my_list_of_list =[[1,2,3],[0,2],[1,3]]
my list=[0,1,2]

I want following output:

dictinoary={[0,1,2]:0 , [0,2]: 1 ,[1,3]:2}

I can do it with two list but I can not if one of them is list with more lists embedded.

Federico Baù
  • 2,100
  • 3
  • 10
  • 20
umut
  • 11
  • 1

1 Answers1

1

You cant use lists as keys in a dictionary since they are not hashable.

A workaround could be to cast the list keys from my_list_of_list into tuples:

>>> my_list_of_list = [[1, 2, 3], [0, 2], [1, 3]]
>>> my_list = [0, 1, 2]
>>> dictinoary = {tuple(k): v for k, v in zip(my_list_of_list, my_list)}
>>> dictinoary
{(1, 2, 3): 0, (0, 2): 1, (1, 3): 2}

Or alternatively into strings:

>>> dictinoary = {str(k): v for k, v in zip(my_list_of_list, my_list)}
>>> dictionary
{'[1, 2, 3]': 0, '[0, 2]': 1, '[1, 3]': 2}
Sash Sinha
  • 11,515
  • 3
  • 18
  • 35