Skip to main content

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

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

Here's a step-by-step tutorial on how to convert a dictionary to a dictionary of arrays in Python:

Step 1: Creating a Sample Dictionary

Let's start by creating a sample dictionary to work with. For this tutorial, we'll assume we have a dictionary that represents students and their respective grades:

grades = {'John': 85, 'Alice': 92, 'Bob': 78, 'Emily': 90}

Step 2: Importing the Required Module

To convert the dictionary to a dictionary of arrays, we need to import the defaultdict class from the collections module. This class allows us to create a dictionary with default values, which will be arrays in our case. Include the following import statement at the beginning of your code:

from collections import defaultdict

Step 3: Converting the Dictionary

Now, let's convert the dictionary to a dictionary of arrays. We'll create a new dictionary and iterate over the original dictionary, assigning each value to the corresponding array in the new dictionary. Use the following code snippet:

array_dict = defaultdict(list)
for key, value in grades.items():
array_dict[key].append(value)

Here, we create a new dictionary called array_dict using defaultdict(list). This ensures that the default value for each key in array_dict is an empty list. We then iterate over the original dictionary using the items() method, which gives us both the key and value for each pair. We use the append() method to add each value to the corresponding array in array_dict.

Step 4: Accessing the Converted Dictionary

Now that we have converted the dictionary, we can access the values as arrays. For example, to print the grades of each student in the array_dict, use the following code:

for key, value in array_dict.items():
print(key, value)

This will output:

John [85]
Alice [92]
Bob [78]
Emily [90]

Additional Tips:

  • If you want to convert a dictionary to a dictionary of arrays with multiple values per key, you can modify the code in Step 3 to handle multiple values. Instead of using append(), you can use any other list methods like extend() to add multiple values to the array.
  • Remember to import the defaultdict class from the collections module at the beginning of your code.

That's it! You have successfully converted a dictionary to a dictionary of arrays in Python. Feel free to modify the code according to your specific requirements.