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
# Python3 code to demonstrate working of # Unlist Single Valued Dictionary List # Using loop + isinstance() # Initializing list test_list = [{ 'Gfg' : 1 , 'is' : [{ 'a' : 2 , 'b' : 3 }]}, { 'best' : [{ 'c' : 4 , 'd' : 5 }], 'CS' : 6 }] # Printing original list print ( "The original list is : " + str (test_list)) # Using loop + isinstance() for dicts in test_list: for key, val in dicts.items(): # Checking for list to convert # isinstance() function if isinstance (val, list ): dicts[key] = val[ 0 ] # Printing result print ( "The converted Dictionary list : " + str (test_list)) |
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
# Python3 code to demonstrate working of # Unlist Single Valued Dictionary List # Using list comprehension + isinstance() # Initializing list test_list = [{ 'Gfg' : 1 , 'is' : [{ 'a' : 2 , 'b' : 3 }]}, { 'best' : [{ 'c' : 4 , 'd' : 5 }], 'CS' : 6 }] # Printing original list print ( "The original list is : " + str (test_list)) # Similar way as above, extracting first element of list # using list comprehension + isinstance() function res = [{key: val[ 0 ] if isinstance (val, list ) else val for key, val in sub.items()} for sub in test_list] # Printing the result print ( "The converted Dictionary list : " + str (res)) |
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
# Python3 code to demonstrate working of # Unlist Single Valued Dictionary List # Using nested for loop # Initializing list test_list = [{ 'Gfg' : 1 , 'is' : [{ 'a' : 2 , 'b' : 3 }]}, { 'best' : [{ 'c' : 4 , 'd' : 5 }], 'CS' : 6 }] # Printing original list print ( "The original list is : " + str (test_list)) # Using nested for loop 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) # Printing result print ( "The converted Dictionary list : " + str (res)) |
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
# Python3 code to demonstrate working of # Unlist Single Valued Dictionary List # Using recursion # Initializing list test_list = [{ 'Gfg' : 1 , 'is' : [{ 'a' : 2 , 'b' : 3 }]}, { 'best' : [{ 'c' : 4 , 'd' : 5 }], 'CS' : 6 }] # Printing original list print ( "The original list is : " + str (test_list)) # Flatten and Unlisting the dictionary list # Using recursion 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) # Printing the resultant list print ( "The converted Dictionary list : " + str (res)) |
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.