Convert Value List Elements to List Records - Python
Last Updated :
21 Jan, 2025
We are given a dictionary with lists as values and the task is to transform each element in these lists into individual dictionary records. Specifically, each list element should become a key in a new dictionary with an empty list as its value.
For example, given {'gfg': [4, 5], 'best': [8, 10, 7, 9]}, the output should be {'gfg': [{4: []}, {5: []}], 'best': [{8: []}, {10: []}, {7: []}, {9: []}]}.
Using enumerate()
This brute-force method iterates through all values (lists) in the dictionary and for each element in the list it creates a new dictionary with the element as the key and an empty list as its value. The enumerate()
function is used to track the index while iterating allowing us to replace each element directly.
Python
d = {'gfg': [4, 5], 'is': [8], 'best': [10]}
# Transforming list elements into dictionaries
for li in d.values():
for i, v in enumerate(li):
li[i] = {v: []}
print(d)
Output{'gfg': [{4: []}, {5: []}], 'is': [{8: []}], 'best': [{10: []}]}
Explanation:
- Outer loop iterates over all lists in the dictionary's values.
- Inner loop replaces each list element with a dictionary
{element: []}
using its index (i
).
Using dictionary comprehension
In this method we utilize dictionary comprehension to create a new dictionary where the items()
function is used to iterate over key-value pairs of the original dictionary. For each list in the values, a nested list comprehension converts its elements into dictionaries {element: []}
.
Python
d = {'gfg': [4, 5], 'is': [8], 'best': [10]}
# Transforming list elements into dictionaries
res = {k: [{v: []} for v in li] for k, li in d.items()}
print(res)
Output{'gfg': [{4: []}, {5: []}], 'is': [{8: []}], 'best': [{10: []}]}
Explanation:
- Outer dictionary comprehension iterates over key-value pairs (
k
, li
) using items()
. - Inner list comprehension converts each element (
v
) in the list (li
) into a dictionary {v: []}
.
Using Recursive Method
We can solve the given problem with recursion by traversing the dictionary and checking if the value is a list, then convert each element into a dictionary with the element as the key and an empty list as its value but if the value is a dictionary then recursively process it.
Python
# Recursive function to convert list elements to dictionaries
def convert_to_list(d):
for k in d:
if isinstance(d[k], list):
d[k] = [{v: []} if not isinstance(v, dict) else v for v in d[k]]
elif isinstance(d[k], dict):
convert_to_list_records(d[k])
return d
d = {'gfg': [4, 5], 'is': [8], 'best': [10]}
res = convert_to_list_records(d)
print(res)
Output{'gfg': [{4: []}, {5: []}], 'is': [{8: []}], 'best': [{10: []}]}
Explanation:
- Function
convert_to_list
iterates through the dictionary, If a value is a list then it converts each element into a dictionary with an empty list and if the value is a dictionary then it calls itself to process that dictionary. - When the value is a list then each element is converted to a dictionary
{v: []}
if it's not already a dictionary.
Similar Reads
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
Convert Each List Element to Key-Value Pair - Python We are given a list we need to convert it into the key- value pair. For example we are given a list li = ['apple', 'banana', 'orange'] we need to convert it to key value pair so that the output should be like {1: 'apple', 2: 'banana', 3: 'orange'}. We can achieve this by using multiple methods like
3 min read
Python - Convert List to Single valued Lists in Tuple Conversion of data types is the most common problem across CS domain nowdays. One such problem can be converting List elements to single values lists in tuples. This can have application in data preprocessing domain. Let's discuss certain ways in which this task can be performed. Input : test_list =
7 min read
Convert 1D list to 2D list of variable length- Python The task of converting a 1D list to a 2D list of variable length in Python involves dynamically dividing a single list into multiple sublists, where each sublist has a different number of elements based on a specified set of lengths.For example, given a list [1, 2, 3, 4, 5, 6] and length specificati
4 min read
Convert Float String List to Float Values-Python The task of converting a list of float strings to float values in Python involves changing the elements of the list, which are originally represented as strings, into their corresponding float data type. For example, given a list a = ['87.6', '454.6', '9.34', '23', '12.3'], the goal is to convert ea
3 min read