Skip to main content

How to convert a dictionary to a dictionary of lists in Python

How to convert a dictionary to a dictionary of lists in Python.

Here is a step-by-step tutorial on how to convert a dictionary to a dictionary of lists in Python:

Step 1: Initialize the original dictionary

  • Start by creating a dictionary with key-value pairs. Each key should be unique.

    original_dict = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3'
    }

Step 2: Create an empty dictionary of lists

  • Create an empty dictionary to store the converted data.

    list_dict = {}

Step 3: Iterate through the original dictionary

  • Use a for loop to iterate over each key-value pair in the original dictionary.

    for key, value in original_dict.items():
    # Code to convert dictionary to list goes here

Step 4: Check if the key already exists in the new dictionary

  • Inside the for loop, check if the key already exists in the new dictionary.

  • If the key exists, append the current value to the list corresponding to that key.

  • If the key does not exist, create a new list with the current value and assign it to the key.

    for key, value in original_dict.items():
    if key in list_dict:
    list_dict[key].append(value)
    else:
    list_dict[key] = [value]

Step 5: Verify the converted dictionary of lists

  • To ensure the conversion was successful, print the new dictionary.

    print(list_dict)

Step 6: Complete code example

  • Here's the complete code example to convert a dictionary to a dictionary of lists:

    original_dict = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3'
    }

    list_dict = {}

    for key, value in original_dict.items():
    if key in list_dict:
    list_dict[key].append(value)
    else:
    list_dict[key] = [value]

    print(list_dict)

That's it! You have successfully converted a dictionary into a dictionary of lists in Python.