Nobi
Nobi

Reputation: 1109

Converting nested lists to dictionary

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'

Upvotes: 1

Views: 148

Answers (3)

thefourtheye
thefourtheye

Reputation: 239653

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.

Upvotes: 4

kostya
kostya

Reputation: 9569

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

Upvotes: 2

Fredrik Pihl
Fredrik Pihl

Reputation: 45670

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.

Upvotes: 2

Related Questions