Open In App

Python – Nested Records List from Lists

Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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))


Output

The 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))


Output

The 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


Output

The 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))


Output

The 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)



Last Updated : 06 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads