Python - Values from custom List in Records
Last Updated :
05 Jun, 2023
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))
Output : 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)
Output[['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))
Output[['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.
Similar Reads
Python - Value Dictionary from Record List
Sometimes, while working with Python Records lists, we can have problems in which, we need to reform the dictionary taking just values of the binary dictionary. This can have applications in many domains which work with data. Let us discuss certain ways in which this task can be performed. Method #1
6 min read
Python - Extract Preceding Record from list values
Sometimes, while working with Tuple records, we can have a problem in which we need to extract the record, which is preceding to particular key provided. This kind of problem can have application in domains such as web development and day-day programming. Let's discuss certain ways in which this tas
9 min read
Python - Convert Uneven Lists into Records
Sometimes, while working with Records, we can have a problem, that we have keys in one list and values in other. But sometimes, values can be multiple in order, like the scores or marks of particular subject. This type of problem can occur in school programming and development domains. Lets discuss
3 min read
Python - Tuple key detection from value list
Sometimes, while working with record data, we can have a problem in which we need to extract the key which has matching value of K from its value list. This kind of problem can occur in domains that are linked to data. Lets discuss certain ways in which this task can be performed. Method #1 : Using
6 min read
Python - Records with Value at K index
Sometimes, while working with records, we might have a problem in which we need to find all the tuples of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Letâs discuss c
8 min read
Python | Index minimum value Record
In Python, we can bind structural information in the form of tuples and then can retrieve the same, and has manyfold applications. But sometimes we require the information of a tuple corresponding to a minimum value of another tuple index. This functionality has many applications such as ranking. Le
4 min read
Python - Nested Records List from Lists
Sometimes, while working with Python Data, we can have problems in which we have data incoming in different formats. In this, we can receive data as key and value in separate dictionaries and we are required to make values as list of records with a new key. Let's discuss certain ways in which we can
6 min read
Python - Rear element extraction from list of tuples records
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print specific information from the tuple like rear index. For instance, a piece of code would want just names to be printed on all the student data. Let's discuss certain ways in which one
8 min read
Column Average in Record List - Python
Given a list of records where each record contains multiple fields, the task is to compute the average of a specific column. Each record is represented as a dictionary or a list, and the goal is to extract values from the chosen column and calculate their average. Letâs explore different methods to
3 min read
Python - Maximum value in record list as tuple attribute
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the max of a list as a tuple attribute. Letâs discuss certai
8 min read