Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

forkey, valueinzip(n1,n2):
    printkey, 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
printdict(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.

Solution 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.

Solution 3:

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

Post a Comment for "Converting Nested Lists To Dictionary"