How To Add Multiple Values To Same Key In Dictionary Python

In Python, a dictionary is a mutable and unordered collection of key-value pairs. In some cases, you might need to map a single key to multiple values. In this tutorial, we will learn how to add multiple values to the same key in a dictionary in Python.

Using Lists

Step 1: Create an empty dictionary

First, create an empty dictionary by using the curly braces ({}). This will be used to store our key-values pairs.

Step 2: Add values to keys in the dictionary

To add multiple values to a key, use a list as the value. If a key does not exist in the dictionary, initialize it with a list containing the value. If the key already exists, append the value to the list.

Step 3: Test adding values to keys

Now we can use the add_value_to_key function to add values to our dictionary.

This will output:

{'A': [1, 3], 'B': [2, 5], 'C': [4]}

As you can see, the values are added as lists to the respective keys in the dictionary.

Using defaultdict from collections

Another approach to add multiple values to the same key in a dictionary is by using the defaultdict class from the collections module. defaultdict is a subclass of the built-in dict class which overrides the __missing__(key) method, providing a default value for a nonexistent key.

Step 1: Import defaultdict

Import the defaultdict class from the collections module

Step 2: Create a defaultdict with a list as the default factory

This creates a new dictionary-like object, where the default factory function is list. The factory function is called when a key is not found in the dictionary.

Step 3: Add values to keys in the defaultdict

To add values to a key, simply append the new value to the list.

This will produce the same output as before:

defaultdict(<class 'list'="">, {'A': [1, 3], 'B': [2, 5], 'C': [4]})

Here, the values are added as lists to the respective keys in the defaultdict, just like in the first method. Note that the defaultdict object is displayed with its default factory function.

Full Code

This code demonstrates both ways of adding multiple values to the same key in a dictionary in Python.

Conclusion

In this tutorial, we learned two methods of adding multiple values to the same key in a dictionary in Python: by using lists and by using the defaultdict class from the collections module. Both methods are easy to implement and suitable for various use cases when you need to store multiple values for a single key in a dictionary.