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'

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.