Given a list of dictionaries, we want to convert single-element list values into direct dictionary records while preserving the overall structure. For example,
Input : a = [{'best': [{'a': 6}], 'Gfg': 15}]
Output : [{'best': {'a': 6}, 'Gfg': 15}]
Explanation : The value list associated with 'best' key is changed to dictionary.
Input : a = [{'Gfg': [{'best' : 17}]}]
Output : [{'Gfg': {'best': 17}}]
Explanation : 'Gfg' key's value changed to single dictionary.
Using loop + isinstance()
We are given a dictionary containing mixed data types, including lists as values. To unlist single-valued lists, we iterate through each dictionary, check if a value is a list using isinstance(), and replace it with its first element using val[0]. This ensures a cleaner structure while preserving other values.
a = [{'Gfg': 1,'is': [{'a': 2, 'b': 3}]}, {'best': [{'c': 4, 'd': 5}], 'CS': 6}]
# Using loop + isinstance()
for dicts in a:
for key, val in dicts.items():
# Checking for list to convert
if isinstance(val, list):
dicts[key] = val[0]
print(str(a))
Output
The converted Dictionary list : [{'Gfg': 1, 'is': {'a': 2, 'b': 3}}, {'best': {'c': 4, 'd': 5}, 'CS': 6}]
Explanation: isinstance(val, list) function checks if the value associated with a key is a list. If it is, dicts[key] = val[0] replaces the list with its first element, effectively unlisting single-valued lists in the dictionary.
Table of Content
Using update() + isinstance()
We can use update() with isinstance() function to achieve the result in a very concise way, here's how.
a = [{'Gfg': 1, 'is': [{'a': 2, 'b': 3}]}, {'best': [{'c': 4, 'd': 5}], 'CS': 6}]
# Using list comprehension to replace single-element lists
for d in a:
d.update({k: v[0] if isinstance(v, list) and len(v) == 1 else v for k, v in d.items()})
print(a)
Output
Converted Dictionary list: [{'Gfg': 1, 'is': {'a': 2, 'b': 3}}, {'best': {'c': 4, 'd': 5}, 'CS': 6}]
Explanation: For each dictionary, we check if a value is a list using isinstance(v, list). If it's a single-element list, we replace it with v[0], otherwise the value remains unchanged.
Using dictionary comprehension
To simplify the structure, we iterate through each dictionary and check if a value is a list with a single dictionary inside it. If so, we replace it with the dictionary itself; otherwise, we retain the original value.
a = [{'Gfg': 1, 'is': [{'a': 2, 'b': 3}]},n{'best': [{'c': 4, 'd': 5}], 'CS': 6}]
# Using nested loop
res = []
for sub in a:
temp = {k: v[0] if isinstance(v, list) and len(v) == 1 and isinstance(v[0], dict) else v for k, v in sub.items()}
res.append(temp)
print(res)
Output
The converted Dictionary list : [{'Gfg': 1, 'is': {'a': 2, 'b': 3}}, {'best': {'c': 4, 'd': 5}, 'CS': 6}]
Explanation: The code uses dictionary comprehension to iterate over key-value pairs, isinstance(v, list) and len(v) == 1 and isinstance(v[0], dict) checks if a value is a single-element list containing a dictionary, and v[0] extracts and replaces it.