Sometimes, while working with Python records, we can have a problem in which we need to extract the key’s value as the dictionary values required. This can have applications in domains in which we require to reduce the data storage and in the web development domain. Let us discuss certain ways in which this task can be performed.
Method #1: Using dictionary comprehension
This is one of the ways in which we can solve this problem. In this, we iterate the list keys and construct a dictionary of required key-value pairs using dictionary comprehension.
Python3
# Python3 code to demonstrate working of # Mapping key values to Dictionary # Using dictionary comprehension # initializing list test_list = [{ 'name' : 'Manjeet' , 'age' : 23 }, { 'name' : 'Akshat' , 'age' : 22 }, { 'name' : 'Nikhil' , 'age' : 21 }] # printing original list print ( "The original list is : " + str (test_list)) # Mapping key values to Dictionary # Using dictionary comprehension res = {sub[ 'name' ]: sub[ 'age' ] for sub in test_list} # printing result print ( "The flattened dictionary is : " + str ( dict (res))) |
The original list is : [{'name': 'Manjeet', 'age': 23}, {'name': 'Akshat', 'age': 22}, {'name': 'Nikhil', 'age': 21}] The flattened dictionary is : {'Manjeet': 23, 'Akshat': 22, 'Nikhil': 21}
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the using dictionary comprehension which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size as the input list.
Method #2: Using dict() + values()
The combination of the above functions can also be used to solve this problem. In this, we perform conversion to a dictionary using dict() and extract dictionary values using values().
Python3
# Python3 code to demonstrate working of # Mapping key values to Dictionary # Using dict() + values() # initializing list test_list = [{ 'name' : 'Manjeet' , 'age' : 23 }, { 'name' : 'Akshat' , 'age' : 22 }, { 'name' : 'Nikhil' , 'age' : 21 }] # printing original list print ( "The original list is : " + str (test_list)) # Mapping key values to Dictionary # Using dict() + values() res = dict (sub.values() for sub in test_list) # printing result print ( "The flattened dictionary is : " + str ( dict (res))) |
The original list is : [{'name': 'Manjeet', 'age': 23}, {'name': 'Akshat', 'age': 22}, {'name': 'Nikhil', 'age': 21}] The flattened dictionary is : {'Manjeet': 23, 'Akshat': 22, 'Nikhil': 21}
Method 3: Using a for loop
Approach:
- Define a list of dictionaries containing key-value pairs.
- Print the original list of dictionaries.
- Create an empty dictionary to store the flattened key-value pairs.
- Loop through each dictionary in the list.
- For each dictionary, loop through its key-value pairs using the .items() method.
- For each key-value pair, add it to the flattened dictionary using the key as the key and the value as the value.
- Print the resulting flattened dictionary.
Python3
# Python3 code to demonstrate working of # Mapping key values to Dictionary # Using for loop # initializing list test_list = [{ 'name' : 'Manjeet' , 'age' : 23 }, { 'name' : 'Akshat' , 'age' : 22 }, { 'name' : 'Nikhil' , 'age' : 21 }] # printing original list print ( "The original list is : " + str (test_list)) # Mapping key values to Dictionary # Using for loop res = {} for sub in test_list: for key, value in sub.items(): res[key] = value # printing result print ( "The flattened dictionary is : " + str (res)) |
The original list is : [{'name': 'Manjeet', 'age': 23}, {'name': 'Akshat', 'age': 22}, {'name': 'Nikhil', 'age': 21}] The flattened dictionary is : {'name': 'Nikhil', 'age': 21}
Time complexity: O(n*m), where n is the length of test_list and m is the average number of keys in each sub-dictionary.
Auxiliary space: O(m), as we are storing the values of each key in a dictionary.
Method #4: Using dictionary unpacking and a generator expression
Step-by-Step Approach:
- Define the list of dictionaries test_list.
- Create an empty dictionary res to store the flattened dictionary.
- Use a for loop to iterate over each sub-dictionary in test_list.
- Use another for loop to iterate over each key-value pair in the current sub-dictionary.
- Add the key-value pair to the res dictionary.
- Print the res dictionary.
Python3
test_list = [{ 'name' : 'Manjeet' , 'age' : 23 }, { 'name' : 'Akshat' , 'age' : 22 }, { 'name' : 'Nikhil' , 'age' : 21 }] # using dictionary unpacking and a generator expression res = {key: value for sub in test_list for key, value in sub.items()} print ( "The flattened dictionary is:" , res) |
The flattened dictionary is: {'name': 'Nikhil', 'age': 21}
Time Complexity: O(NM), where N is the number of sub-dictionaries in test_list and M is the average number of key-value pairs in each sub-dictionary.
Auxiliary Space: O(NM), since we are creating a dictionary with N*M key-value pairs.
Method #5: Using the reduce() function
In this method to flatten a list of dictionaries into a single dictionary is to use the reduce() function from the functools module. The reduce() function applies a rolling computation to sequential pairs of elements from a list, accumulating the result. In this case, we can use reduce() to merge the dictionaries from the list into a single dictionary.
Approach:
- Import the functools module to use the reduce() function.
- Define a function named merge_dicts that takes two dictionaries as arguments and returns a new dictionary that contains all the key-value pairs from both dictionaries.
- Use the reduce() function to apply the merge_dicts function to each pair of dictionaries in the test_list, accumulating the result in a single dictionary.
- Print the flattened dictionary.
Python3
# Python3 code to demonstrate working of # Mapping key values to Dictionary # Using reduce() # import functools module for using reduce() import functools # initializing list test_list = [{ 'name' : 'Manjeet' , 'age' : 23 }, { 'name' : 'Akshat' , 'age' : 22 }, { 'name' : 'Nikhil' , 'age' : 21 }] # printing original list print ( "The original list is : " + str (test_list)) # define function to merge dictionaries def merge_dicts(d1, d2): return { * * d1, * * d2} # Mapping key values to Dictionary # Using reduce() res = functools. reduce (merge_dicts, test_list) # printing result print ( "The flattened dictionary is : " + str (res)) |
The original list is : [{'name': 'Manjeet', 'age': 23}, {'name': 'Akshat', 'age': 22}, {'name': 'Nikhil', 'age': 21}] The flattened dictionary is : {'name': 'Nikhil', 'age': 21}
Time complexity: O(n), where n is the number of dictionaries in the list.
Auxiliary space: O(n), since we need to store all the key-value pairs in the final dictionary.
Method 6: Using the zip() function and dictionary comprehension
Step by step approach:
Initialize the list of dictionaries – test_list.
Print the original list using print() function.
Use dictionary comprehension with zip() function to map the key-value pairs of each dictionary in the list to a new dictionary – res.
Print the flattened dictionary using print() function.
Python3
# initializing list test_list = [{ 'name' : 'Manjeet' , 'age' : 23 }, { 'name' : 'Akshat' , 'age' : 22 }, { 'name' : 'Nikhil' , 'age' : 21 }] # printing original list print ( "The original list is : " + str (test_list)) # Mapping key values to Dictionary # Using zip() function and dictionary comprehension res = {k: v for sub in test_list for k, v in zip (sub.keys(), sub.values())} # printing result print ( "The flattened dictionary is : " + str (res)) |
The original list is : [{'name': 'Manjeet', 'age': 23}, {'name': 'Akshat', 'age': 22}, {'name': 'Nikhil', 'age': 21}] The flattened dictionary is : {'name': 'Nikhil', 'age': 21}
Time complexity: O(nm), where n is the number of dictionaries in the list and m is the average number of key-value pairs in each dictionary.
Auxiliary space: O(nm), as a new dictionary is created to store the flattened key-value pairs.
Method 7: Using map() and lambda function
In this method, we uses the map() function along with a lambda function to extract the “name” and “age” key-value pairs from the list of dictionaries and creates a new dictionary using those key-value pairs. The resulting dictionary is flattened with a single line of code.
Python3
# Python3 code to demonstrate working of # Mapping key values to Dictionary # Using dictionary comprehension # initializing list test_list = [{ 'name' : 'Manjeet' , 'age' : 23 }, { 'name' : 'Akshat' , 'age' : 22 }, { 'name' : 'Nikhil' , 'age' : 21 }] # printing original list print ( "The original list is : " + str (test_list)) # Mapping key values to Dictionary # Using map() and lambda function res = dict ( map ( lambda sub: (sub[ 'name' ], sub[ 'age' ]), test_list)) # printing result print ( "The flattened dictionary is : " + str (res)) |
The original list is : [{'name': 'Manjeet', 'age': 23}, {'name': 'Akshat', 'age': 22}, {'name': 'Nikhil', 'age': 21}] The flattened dictionary is : {'Manjeet': 23, 'Akshat': 22, 'Nikhil': 21}
Time complexity: O(n )where n is the length of the input list
Auxiliary Space: O(n) where n is the length of the input list