
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert List to List of Dictionaries in Python
Data handling or organizing or structuring in Python has a lot of common tasks and 1 such task is the conversion of list to list of dictionaries. It is a simple process that allows us to associate specific keys with their corresponding values; creating a collection of dictionaries that can be simply accessed and/or manipulated.
Before going forward with the techniques let us 1st see an example input and output. Consider the following:
Input
test_list = ['John', 25, 'Smith', 30, 'Alice', 35] key_list = ['name', 'age']
Output
[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]
Method 1: Using a Loop
In this approach we simply take a list that contains alternating names and ages and convert it to a list of dictionaries wherein each resultant dictionary list represents a person's info with keys for ?name' and ?age'. By running a loop iteration over the original list and then grouping the values based upon the keys provided. The dictionaries created are appended to a list "result".
Example
test_list = ['John', 25, 'Smith', 30, 'Alice', 35] key_list = ['name', 'age'] result = [] for i in range(0, len(test_list), len(key_list)): temp_dict = {} for j, key in enumerate(key_list): temp_dict[key] = test_list[i + j] result.append(temp_dict) print(result)
Output
[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]
Method 2: Using a List Comprehension with Zip()
This is another approach towards our goal and makes use of list comprehensions to convert list to list of dictionaries. It iterates over the test_list in chunks which is determined the length of the key_list thereby creating dictionaries which are paired with elements from key_list with their corresponding elements from the test_list slice. It then finally appends them to the result list which is a list of dictionaries. The zip() function is responsible for the pairing of elements.
Example
test_list = ['John', 25, 'Smith', 30, 'Alice', 35] key_list = ['name', 'age'] result = [{key: value for key, value in zip(key_list, test_list[i:i+len(key_list)])} for i in range(0, len(test_list), len(key_list))] print(result)
Output
[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]
Method 3: Using a List Comprehension with Slicing
This method also makes use of list comprehensions to iterate over the test_list (created at the start of the code) in increments of the length of the key_list. Inside of the list comprehension, we have a dictionary comprehension which creates dictionaries by pairing the keys from the key_list with the help of the values present in test_list using indexing.
Example
test_list = ['John', 25, 'Smith', 30, 'Alice', 35] key_list = ['name', 'age'] result = [{key_list[j]: test_list[i+j] for j in range(len(key_list))} for i in range(0, len(test_list), len(key_list))] print(result)
Output
[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]
Method 4: Using Itertools.islice() and Iter()
It is common in Python to use itertools for iterations. One of its functions, islice(), allows us to extract a specific portion of an iterable by specifying the starting and ending indices. By using iter(test_list), we can create an iterator for test_list. This iterator can then be used with islice() to extract a specific number of elements from the test_list.
The zip function combines the sliced elements with the key_list. Then, a dictionary comprehension is utilized to create dictionaries. It's important to note that the number of iterations in the code below is determined by a formula: length(test_list) divided by length(key_list).
Example
import itertools test_list = ['John', 25, 'Smith', 30, 'Alice', 35] key_list = ['name', 'age'] iter_test = iter(test_list) result = [{key: value for key, value in zip(key_list, itertools.islice(iter_test, len(key_list)))} for _ in range(len(test_list) // len(key_list))] print(result)
Output
[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]
Method 5: Using a Generator Function
Generator functions are a type of function that can generate a sequence of values and yields them 1 at a time; allowing for efficient memory usage. The yield keyword is used produce values and the function can be iterated over with the help of a simple loop. The below approach defines a generator known as generate_dicts which takes input as test_list and key_list. The dictionaries are generated by pairing elements form the key_list with their corresponding elements in the test_list.
Example
def generate_dicts(test_list, key_list): for i in range(0, len(test_list), len(key_list)): yield {key_list[j]: test_list[i+j] for j in # yield keyword instead of return range(len(key_list))} test_list = ['John', 25, 'Smith', 30, 'Alice', 35] key_list = ['name', 'age'] result = list(generate_dicts(test_list, key_list)) print(result)
Output
[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]
Conclusion
In this article, we have discovered different methods to convert a list into a list of dictionaries in Python. These methods include using loops; list comprehensions with zip(); list comprehension with slicing; itertools.islice() and iter() and lastly generator functions . All these methods offer us flexibility for transforming data into structured format. All the methods have a linear time complexity of O(n).