Transform Dictionary to List of Dictionaries in Python

Prompt

transform dict to list from one json to another json with keys
Python

Result

Sure! Here's a Python code snippet that transforms a dictionary to a list of dictionaries, where each dictionary has the keys from the original dictionary:

import json

def transform_dict_to_list(input_dict):
    """
    Transforms a dictionary to a list of dictionaries with keys from the original dictionary.

    Args:
        input_dict (dict): The input dictionary to transform.

    Returns:
        list: A list of dictionaries with keys from the original dictionary.
    """
    output_list = []
    for key, value in input_dict.items():
        output_list.append({key: value})
    return output_list

# Example usage
input_dict = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

output_list = transform_dict_to_list(input_dict)
output_json = json.dumps(output_list, indent=4)

print(output_json)
Python

This code defines a function transform_dict_to_list that takes an input dictionary and transforms it into a list of dictionaries. Each dictionary in the output list contains a single key-value pair from the original dictionary. The code then demonstrates an example usage by transforming the input_dict and printing the resulting JSON-formatted output.