Andrew Earl Andrew Earl - 7 months ago 25
Python Question

Converting a list of lists into a dictionary of lists

I'm trying to convert a list of lists:

x = [[1, 2], [1, 3], [1, 3, 4], [1, 2, 5]]


to a dictionary of lists where the index of each list is the key of the dictionary (starting at 1):

new_dictionary = {1: [1, 2], 2: [1, 3], 3: [1, 3, 4], 4: [1, 2, 5]}


I will be working with large lists, is there an efficient way of doing this?

Answer

Yes, the dict constructor takes an iterable of tuples, where the first item is the key and the second is the value.

This is exactly what enumerate returns:

new_dictionary = dict(enumerate(x))

Then new_dictionary will contain:

{0: [1, 2], 1: [1, 3], 2: [1, 3, 4], 3: [1, 2, 5]}

Notice that the first key is 0, not 1. If you want to start from one or something else, use the start=1 parameter with enumerate:

>>> dict(enumerate(x, start=1))
{1: [1, 2], 2: [1, 3], 3: [1, 3, 4], 4: [1, 2, 5]}

I am curious about your use case, however, since a list and a dictionary can be used in very similar ways:

>>> x[0]
[1, 2]
>>> new_dictionary[0]
[1, 2]

Are you sure you really need a dictionary for this?

Comments