VOOZH about

URL: https://www.geeksforgeeks.org/python/python-unlist-single-valued-dictionary-list/

⇱ Python - Unlist Single Valued Dictionary List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Unlist Single Valued Dictionary List

Last Updated : 12 Jul, 2025

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 usingisinstance(), and replace it with its first element using val[0]. This ensures a cleaner structure while preserving other values.


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.

Using update() + isinstance()

We can use update() with isinstance() function to achieve the result in a very concise way, here's how.


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.


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.

Comment