Python - Nested Records List from Lists
Last Updated :
06 Dec, 2023
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 convert nested record lists from lists.
Nested List from Lists in Python
Below are the ways by which we can convert nested records list from lists in Python:
Python Nested Records List from Lists Using for loops
In this example, two lists (test_list1
and test_list2
) are employed to create a nested dictionary (res
) using a combination of the zip()
function and a loop. Each element of the first list becomes a key, and the corresponding elements of the second list are transformed into dictionaries with an additional key ('id') within a loop. The resulting dictionaries are then added to the nested structure.
Python3
# initializing lists
test_list1 = ['gfg', 'best']
test_list2 = [[1, 2], [3, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing add_key
add_key = 'id'
# Nested Records List from Lists
# Using zip() + loop
res = dict()
for i in range(0, len(test_list1)):
a = dict()
x = []
for j in range(0, len(test_list2[i])):
a[add_key] = test_list2[i][j]
x.append(a)
res[test_list1[i]] = x
# printing result
print("The constructed dictionary is : " + str(res))
OutputThe original list 1 is : ['gfg', 'best']
The original list 2 is : [[1, 2], [3, 4]]
The constructed dictionary is : {'gfg': [{'id': 2}, {'id': 2}], 'best': [{'id': 4}, {'id': 4}]}
Time complexity: O(n^2)
Auxiliary space: O(n^2)
Nested Records List from Lists in Python Using Dictionary Comprehension
In this example, two lists (test_list1
and test_list2
) are employed to create a nested dictionary (res
) using dictionary comprehension and the zip()
function. Each element of the first list becomes a key, and the corresponding elements of the second list are transformed into dictionaries with an additional key ('id') using a concise dictionary comprehension.
Python3
# initializing lists
test_list1 = ['gfg', 'best']
test_list2 = [[1, 2], [3, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing add_key
add_key = 'id'
# Nested Records List from Lists
# Using dictionary comprehension + zip()
res = {key: [{add_key: idx} for idx in val]
for key, val in zip(test_list1, test_list2)}
# printing result
print("The constructed dictionary is : " + str(res))
OutputThe original list 1 is : ['gfg', 'best']
The original list 2 is : [[1, 2], [3, 4]]
The constructed dictionary is : {'gfg': [{'id': 1}, {'id': 2}], 'best': [{'id': 3}, {'id': 4}]}
Time complexity: O(n)
Auxiliary space: O(n)
Nested Records List from Lists Using zip() and loop
In this example, two lists (test_list1
and test_list2
) are utilized to create a nested dictionary (res
) using a loop and dictionary comprehension, where each element of the first list becomes a key, and the corresponding elements of the second list are transformed into dictionaries with an additional key ('id') using a loop.
Python3
# initializing lists
test_list1 = ['gfg', 'best']
test_list2 = [[1, 2], [3, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing add_key
add_key = 'id'
# Nested Records List from Lists
# Using zip() + loop
res = dict()
for key, val in zip(test_list1, test_list2):
res[key] = [{add_key: idx} for idx in val]
# printing result
print("The constructed dictionary is : " + str(res))
OutputThe original list 1 is : ['gfg', 'best']
The original list 2 is : [[1, 2], [3, 4]]
The constructed dictionary is : {'gfg': [{'id': 1}, {'id': 2}], 'best': [{'id': 3}, {'id': 4}]}
Time complexity: O(n)
Auxiliary space: O(n)
Nested Records List from Lists in Python Using Recursive Method
In this example, a recursive function construct_dict
is defined to create a nested dictionary from two lists (keys
and values
), associating each key with dictionaries containing an additional key-value pair, and the final result is printed.
Python3
def construct_dict(keys, values, key_idx=0, value_idx=0, add_key='id'):
if key_idx >= len(keys) or value_idx >= len(values):
return {}
d = {keys[key_idx]: []}
for i in range(len(values[value_idx])):
d[keys[key_idx]].append({add_key: values[value_idx][i]})
next_d = construct_dict(keys, values, key_idx+1, value_idx+1, add_key)
d.update(next_d)
return d
# initializing lists
test_list1 = ['gfg', 'best']
test_list2 = [[1, 2], [3, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing add_key
add_key = 'id'
res = construct_dict(test_list1, test_list2, 0, 0)
print("The constructed dictionary is : " + str(res))
# this code contributed by tvsk
OutputThe original list 1 is : ['gfg', 'best']
The original list 2 is : [[1, 2], [3, 4]]
The constructed dictionary is : {'gfg': [{'id': 1}, {'id': 2}], 'best': [{'id': 3}, {'id': 4}]}
Time complexity:O(n*m)
Auxiliary complexity:O(n*m)
Nested Records List from Lists Using itertools.product() and dict()
In this example, two lists (test_list1
and test_list2
) are combined using itertools.product()
to create a Cartesian product of their elements. The result is then transformed into a nested dictionary (result
) using dictionary comprehension, associating each unique combination of keys with dictionaries containing an additional key-value pair ('id').
Python3
import itertools
# initializing lists
test_list1 = ['gfg', 'best']
test_list2 = [[1, 2], [3, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing add_key
add_key = 'id'
# Nested Records List from Lists
# Using itertools.product() and dict()
records = dict(itertools.product(test_list1, test_list2))
result = {k: [{add_key: v} for v in vs] for k, vs in records.items()}
# printing result
print("The constructed dictionary is : " + str(result))
OutputThe original list 1 is : ['gfg', 'best']
The original list 2 is : [[1, 2], [3, 4]]
The constructed dictionary is : {'gfg': [{'id': 3}, {'id': 4}], 'best': [{'id': 3}, {'id': 4}]}
Time complexity: O(n^2), where n is the length of the longest list value in the dictionary
Auxiliary Space: O(n^2)
Similar Reads
Python | Split nested list into two lists
Given a nested 2D list, the task is to split the nested list into two lists such that the first list contains the first elements of each sublist and the second list contains the second element of each sublist. In this article, we will see how to split nested lists into two lists in Python. Python Sp
5 min read
Python | Difference in Record Lists
Sometimes, while working with data, we may have a problem in which we require to find the difference records between two lists that we receive. This is a very common problem and records usually occurs as a tuple. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using list
5 min read
Python - Remove nested records from tuple
Sometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to remove the nested records. This is a problem which does not occur commonly, but having a solution to it is useful. Letâs discuss certain way in which this task c
5 min read
Python - How to copy a nested list
We are given a nested list we need to copy it. For example, we are given a nested list a = [[1, 2], [3, 4], [5, 6]] and we need to copy it so that output should be [[1, 2], [3, 4], [5, 6]]. Using a For LoopTo copy a nested list using a for loop, we iterate over each sublist and create a new list for
2 min read
Python - Values from custom List in Records
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
7 min read
Python | Convert given list into nested list
Sometimes, we come across data that is in string format in a list and it is required to convert it into a list of the list. This kind of problem of converting a list of strings to a nested list is quite common in web development. Let's discuss certain ways in which this can be performed. Convert the
4 min read
Concatenate All Records - Python
The task of concatenating all records in Python involves combining elements from a list, typically strings, into a single unified string. The goal is to concatenate each individual element, ensuring that the result is a continuous string without spaces or delimiters, unless specified. For example, g
3 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 | Maximize Record list
Sometimes, while working with Python records, we can have a problem in which we need to perform cross maximization of list of tuples. This kind of application is popular in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using list comprehension +
6 min read
Python - Value nested grouping on List
Sometimes, while working with data, we can have a problem in which we have flat data in the form of a list of dictionaries, and we need to perform the categorization from that bare dictionaries according to ids. This can have applications in domains that involve data, such as web development and Dat
6 min read