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…

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

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…

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…

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

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

Tags:,
One Comment

Add a Comment

Your email address will not be published. Required fields are marked *