Python – Unlist Single Valued Dictionary List
Given a list of dictionaries, perform the unlisting of records in which we just have 1 dictionary as record element.
Input : test_list = [{'best': [{'a': 6}], 'Gfg': 15}]
Output : [{'best': {'a': 6}, 'Gfg': 15}]
Explanation : The value list associated with 'best' key is changed to dictionary.
Input : test_list = [{'Gfg': [{'best' : 17}]}]
Output : [{'Gfg': {'best': 17}}]
Explanation : 'Gfg' key's value changed to single dictionary.
Method #1: Using loop + isinstance()
This is a brute-force way in which this task can be performed. In this, we test for the list type using isinstance(), and loop is used for iterations.
Python3
test_list = [{ 'Gfg' : 1 ,
'is' : [{ 'a' : 2 , 'b' : 3 }]},
{ 'best' : [{ 'c' : 4 , 'd' : 5 }],
'CS' : 6 }]
print ( "The original list is : " + str (test_list))
for dicts in test_list:
for key, val in dicts.items():
if isinstance (val, list ):
dicts[key] = val[ 0 ]
print ( "The converted Dictionary list : " + str (test_list))
|
Output :
The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}]
The converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}]
Time complexity: O(N*M), where n is the length of the outer list and m is the maximum length of a list inside the dictionaries of the outer list.
Auxiliary Space: O(1), since the program does not create any additional data structures proportional to the input size. It only modifies the existing list in place.
Method #2: Using list comprehension + isinstance()
The combination of the above functions can be used to solve the problem. In this, we perform a similar task with a shorthand approach similar to the above method.
Python3
test_list = [{ 'Gfg' : 1 ,
'is' : [{ 'a' : 2 , 'b' : 3 }]},
{ 'best' : [{ 'c' : 4 , 'd' : 5 }],
'CS' : 6 }]
print ( "The original list is : " + str (test_list))
res = [{key: val[ 0 ] if isinstance (val, list ) else val
for key, val in sub.items()}
for sub in test_list]
print ( "The converted Dictionary list : " + str (res))
|
Output :
The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}]
The converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}]
Time complexity: O(N*M), where n is the length of the outer list and m is the maximum length of a list inside the dictionaries of the outer list.
Auxiliary Space: O(N), where n is the number of elements in the list “test_list”.
Method 3: Using a nested for loop and checking the type of the value.
Python3
test_list = [{ 'Gfg' : 1 ,
'is' : [{ 'a' : 2 , 'b' : 3 }]},
{ 'best' : [{ 'c' : 4 , 'd' : 5 }],
'CS' : 6 }]
print ( "The original list is : " + str (test_list))
res = []
for sub in test_list:
temp = {}
for key, val in sub.items():
if isinstance (val, list ) and len (val) = = 1 and isinstance (val[ 0 ], dict ):
temp[key] = val[ 0 ]
else :
temp[key] = val
res.append(temp)
print ( "The converted Dictionary list : " + str (res))
|
Output
The original list is : [{'Gfg': 1, 'is': [{'a': 2, 'b': 3}]}, {'best': [{'c': 4, 'd': 5}], 'CS': 6}]
The converted Dictionary list : [{'Gfg': 1, 'is': {'a': 2, 'b': 3}}, {'best': {'c': 4, 'd': 5}, 'CS': 6}]
Time complexity: O(NM) where N is the number of dictionaries in the list and M is the maximum number of keys in a dictionary.
Auxiliary space: O(NM) because we are creating a new list of dictionaries with the same number of keys and values as the original list.
Method 4: Using recursion to flatten and unlist the dictionary list
Approach:
- Define a function that takes a dictionary or list as input and returns the flattened and unlisted version of it.
- Check if the input is a dictionary. If it is, then iterate over its keys and values.
- If the value is a dictionary or list, call the function recursively on that value to flatten and unlist it.
- If the value is a list with only one element, then return that element.
- If the value is not a dictionary or list, return the value.
- If the input is a list, then iterate over its elements and call the function recursively on each element.
- Return the flattened and unlisted list.
Python3
test_list = [{ 'Gfg' : 1 ,
'is' : [{ 'a' : 2 , 'b' : 3 }]},
{ 'best' : [{ 'c' : 4 , 'd' : 5 }],
'CS' : 6 }]
print ( "The original list is : " + str (test_list))
def unlist_dict_list( input ):
if isinstance ( input , dict ):
return {key: unlist_dict_list(val) for key, val in input .items()}
elif isinstance ( input , list ):
if len ( input ) = = 1 :
return unlist_dict_list( input [ 0 ])
else :
return [unlist_dict_list(elem) for elem in input ]
else :
return input
res = unlist_dict_list(test_list)
print ( "The converted Dictionary list : " + str (res))
|
Output
The original list is : [{'Gfg': 1, 'is': [{'a': 2, 'b': 3}]}, {'best': [{'c': 4, 'd': 5}], 'CS': 6}]
The converted Dictionary list : [{'Gfg': 1, 'is': {'a': 2, 'b': 3}}, {'best': {'c': 4, 'd': 5}, 'CS': 6}]
Time complexity: O(N), where n is the total number of elements in the dictionary list.
Auxiliary space: O(N), where n is the total number of elements in the dictionary list.
Last Updated :
03 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...