Sometimes, while working with Python records, we can have a problem in which we need to extract all the values from the custom list in list dictionary records. This problem can have applications in domains such as web development and school programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [{‘name’ : ‘Gfg’, ‘id’ : 1, ‘Score’ : 3}, {‘name’ : ‘is’, ‘id’ : 4, ‘Score’ : 10}, {‘name’ : ‘Best’, ‘Score’ : 12}] get_list = [‘name’]
Output : [[‘Gfg’], [‘is’], [‘Best’]]Input : test_list = [{‘name’ : ‘Gfg’, ‘id’ : 1, ‘Score’ : 3}, {‘name’ : ‘is’, ‘id’ : 4, ‘Score’ : 10}, {‘name’ : ‘Best’, ‘Score’ : 12}] get_list = [‘Serial’]
Output : [[None], [None], [None]]
Method #1: Using list comprehension + get()
The combination of above functions can be used to solve this problem. In this, we perform the task of iterating through each dictionary using list comprehension and get() is used to fetch dictionary values and also handle non present values.
Python3
# Python3 code to demonstrate working of # Values from custom List in Records # Using list comprehension + get() # initializing list test_list = [{ 'name' : 'Gfg' , 'id' : 1 , 'Score' : 3 }, { 'name' : 'is' , 'id' : 4 , 'Score' : 10 }, { 'name' : 'Best' , 'Score' : 12 }] # printing original list print ( "The original list : " + str (test_list)) # initializing Get list get_list = [ 'name' , 'id' ] # Values from custom List in Records # Using list comprehension + get() res = [ list (idx.get(sub) for sub in get_list) for idx in test_list] # printing result print ( "All extracted values : " + str (res)) |
Output:
The original list : [{'name': 'Gfg', 'id': 1, 'Score': 3}, {'name': 'is', 'id': 4, 'Score': 10}, {'name': 'Best', 'Score': 12}] All extracted values : [['Gfg', 1], ['is', 4], ['Best', None]]
Time complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(m*n), where m is the length of the get_list and n is the length of the input list. This is because we create a new list of length m for each record in the input list to hold the values extracted using the get() method.
Method #2: Using list comprehension + itemgetter() + intersection()
The combination of above functions can be used to solve this problem. In this, we use itemgetter() and intersection() to get the value checking both target list and argument list. Can’t handle not present keys.
Python3
# Python3 code to demonstrate working of # Values from custom List in Records # Using list comprehension + itemgetter() + intersection() from operator import itemgetter # initializing list test_list = [{ 'name' : 'Gfg' , 'id' : 1 , 'Score' : 3 }, { 'name' : 'is' , 'id' : 4 , 'Score' : 10 }] # printing original list print ( "The original list : " + str (test_list)) # initializing Get list get_list = [ 'name' , 'id' ] # Values from custom List in Records # Using list comprehension + itemgetter() + intersection() res = [ list (itemgetter( * set (get_list).intersection(idx))(idx)) for idx in test_list] # printing result print ( "All extracted values : " + str (res)) |
The original list : [{'name': 'Gfg', 'id': 1, 'Score': 3}, {'name': 'is', 'id': 4, 'Score': 10}] All extracted values : [[1, 'Gfg'], [4, 'is']]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. list comprehension + itemgetter() + intersection() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #3: Using append + list+ get
Iterate over the list and find the key value that matches to the get_list and append those values to another list.
Step-by-Step algorithm
- We first define the input list of dictionaries and the list of keys to extract.
- We then initialize an empty list to store the output.
- We then use a loop to iterate over each dictionary in the input list, and for each dictionary,
- We initialize an empty list to store the extracted values.
- We then use a nested loop to iterate over each key in the specified list of keys, and for each key, we use the get() method to extract the value for the current key from the current dictionary, with a default value of None if the key is not present in the dictionary.
- We then append the extracted value to the list of values for the current dictionary. Finally, we append the list of values for the current dictionary to the output list.
Python3
# Define the input list of # dictionaries and the list of keys to extract test_list = [{ 'name' : 'Gfg' , 'id' : 1 , 'Score' : 3 }, { 'name' : 'is' , 'id' : 4 , 'Score' : 10 }, { 'name' : 'Best' , 'Score' : 12 }] get_list = [ 'name' ] # Initialize an empty list to store the output output_list = [] # Iterate over each dictionary # in the input list for d in test_list: # Initialize an empty list # to store the extracted values values = [] # Iterate over each key in the # specified list of keys for key in get_list: # Use the get() method to extract # the value for the current key value = d.get(key, None ) # Append the extracted value to the list of values values.append(value) # Append the list of values for # the current dictionary to the output list output_list.append(values) # Print the output list print (output_list) |
[['Gfg'], ['is'], ['Best']]
Time complexity: O(NM), where N is the length of the input list of dictionaries and M is the length of the list of keys to extract. This is because we iterate over each dictionary in the input list and then iterate over each key in the specified list of keys, resulting in a nested loop.
Space complexity: O(NM), where N is the length of the input list of dictionaries and M is the length of the list of keys to extract. This is because we initialize an empty list to store the output and then create a list of values for each dictionary in the input list, resulting in a nested list structure with N sublists, each containing M values.
Method #4: Using lambda
This approach using a lambda function with nested list comprehension. The lambda function takes two arguments, the list of dictionaries lst, and the list of keys to retrieve keys. A list comprehension is used to iterate over the list of dictionaries and retrieve the values for each key in the keys list.
Algorithm
1. Define a lambda function that takes two arguments, a list of dictionaries lst, and a list of keys to retrieve keys.
2. Use a nested list comprehension to iterate over the list of dictionaries and retrieve the values for each key in the keys list.
3. Return the resulting list of lists.
Python3
test_list = [{ 'name' : 'Gfg' , 'id' : 1 , 'Score' : 3 }, { 'name' : 'is' , 'id' : 4 , 'Score' : 10 }, { 'name' : 'Best' , 'Score' : 12 }] get_list = [ 'name' ] result = lambda lst, keys: [[d.get(key) for key in keys] for d in lst] print (result(test_list, get_list)) |
[['Gfg'], ['is'], ['Best']]
Time Complexity: O(n * m), where n is the number of dictionaries in the list and m is the length of the keys list. The nested list comprehension iterates over each dictionary in the list and retrieves the values for each key in the keys list.
Auxiliary Space: O(n * m), where n is the number of dictionaries in the list and m is the length of the keys list. The resulting list of lists contains n sublists, each containing m elements. The space required to store each element in the list is constant.
Method 5: Using the Pandas library
Python3
import pandas as pd # Define the input list of dictionaries test_list = [{ 'name' : 'Gfg' , 'id' : 1 , 'Score' : 3 }, { 'name' : 'is' , 'id' : 4 , 'Score' : 10 }, { 'name' : 'Best' , 'Score' : 12 }] # Create a DataFrame from the input list df = pd.DataFrame(test_list) # Select only the desired keys from the DataFrame output_list = df[ 'name' ].tolist() # Print the output list print (output_list) |
Output:
['Gfg', 'is', 'Best']
Time complexity: The time complexity of this method is O(n), where n is the number of dictionaries in the input list.
Auxiliary space: The auxiliary space complexity is O(n), where n is the number of dictionaries in the input list, due to the creation of the DataFrame.