1

Hi please I try to make a dictionary out of the nested lists below and I get a TypeError. Please help me fix it to get the desired output as shown below. Thanks

n1 = [[1,2],[3,4]]
n2 = [[(5,7),(10,22)],[(6,4),(8,11)]]

output = {1:(5,7), 2:(10,22), 3:(6,4), 4:(8,11)}

D1 = {}
for key, value in zip(n1,n2):
    D1[key] = value
print D1 

TypeError: unhashable type: 'list'
Nobi
  • 1,113
  • 4
  • 23
  • 41

3 Answers3

4

Your approach didn't work, because when you zip n1 and n2, the result will be like this

for key, value in zip(n1,n2):
    print key, value
# [1, 2] [(5, 7), (10, 22)]
# [3, 4] [(6, 4), (8, 11)]

So, key is a list. But, it is not hashable. So it cannot be used as an actual key to a dictionary.

You can chain the nested lists to get them flattened and then you can zip them together with izip

from itertools import chain, izip
print dict(izip(chain.from_iterable(n1), chain.from_iterable(n2)))
# {1: (5, 7), 2: (10, 22), 3: (6, 4), 4: (8, 11)}

The beauty of this method is that, it will be very memory efficient, as it doesn't create any intermediate lists. So, this can be used even when the actual lists are very large.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

Perhaps not the most pythonic way, but it's short:

In [8]: dict(zip(sum(n1, []), sum(n2, [])))
Out[8]: {1: (5, 7), 2: (10, 22), 3: (6, 4), 4: (8, 11)}

The sum() trick, is used for flattening the list.

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
2

Try this:

from itertools import chain
n1 = [[1,2],[3,4]]
n2 = [[(5,7),(10,22)],[(6,4),(8,11)]]
print dict(zip(chain(*n1), chain(*n2))
kostya
  • 9,221
  • 1
  • 29
  • 36