how to convert list of lists to dictionary in python

Introduction

Converting a list of lists to a dictionary can be useful in certain situations. We can think of a Python list of lists as a database table where the outer list represent the table and the inner lists represent the rows. A database table has a primary key and the rest of the fields hold the data. We can use that key as a dictionary key and the rest of data as the value. Let us see how to do that in Python....

Dictionary comprehension

Dictionary comprehensions in Python is a cool technique to produce dictionary data structures in a neat way. Assume we have a list of cars in a list of lists format. We need to convert that into a dictionary format. For each list we extract the first item as the key and the rest of the items as the value list. Extracting the key is as simple as indexing an array. Extracting the rest of items can be achieved using slicing. Take a look...


# List of lists
cars_list = [[1,'Honda','red'], [2,'Toyota','white'], [3,'Mazda','blue']]\
# Convert to dictionary
cars_dict = {car[0]:car[1:] for car in cars_list}
# Print output
print (cars_dict)
print (cars_dict[1])

If you execute the code snippet above, you should get the following output...

{1: ['Honda', 'red'], 2: ['Toyota', 'white'], 3: ['Mazda', 'blue']}
['Honda', 'red']

Generator expression

Again almost the same format but using a generator expression to construct a dictionary object. For more information about iterators and generators you may check the following article. Here is an example...

cars_list = [[1,'Honda','red'], [2,'Toyota','white'], [3,'Mazda','blue']]
cars_dict = dict((car[0], car[1:]) for car in cars_list)
print (cars_dict)
print (cars_dict[1])

Regular for loop

The same logic but using a regular loop is demonstrated below. Nothing drastically different except the coding style. Here is an example...

# List of lists
cars_list = [[1,'Honda','red'], [2,'Toyota','white'], [3,'Mazda','blue']]
# Output dictionary
cars_dict = {}

# Convert to dictionary
for car in cars_list:
    cars_dict[car[0]] = car[1:]

# Print to see output
print (cars_dict)
print (cars_dict[1])

We can also compose our for loop in a different style, take a look...

# List of lists
cars_list = [[1,'Honda','red'], [2,'Toyota','white'], [3,'Mazda','blue']]
# Output dictionary
cars_dict = {}

# Convert to dictionary
for key, car, color in cars_list:
    cars_dict[key] = [car, color]

# Print to see output
print (cars_dict)
print (cars_dict[1])

That is all for today. Thanks for reading. Please comment if you have questions.

Leave a Reply