In the Python dictionary, can one key hold more than one value?


What is a Dictionary in Python?

A dictionary is Python’s own indigenous representation of a data structure, and can be considered similar to maps in C++. It is a dynamic data structure which stores key-value pairs dynamically, and is mutable. It can be better understood as an associative array, where each element is associated with its key value.

Can one key hold more than one value?

Although dictionaries in Python store values as key-value pairs, it is possible to store more than one value corresponding to the same key in a dictionary. This is performed by setting containers like lists, sets and tuples as a value object to each key of the dictionary. In this article, we will focus mainly on

Steps to create a dictionary with multiple values for each key

  • Explicit declaration of a list

  • Adding values with extend() function

  • Adding sublists to a list using append() function

  • Adding values using the setdefault() method

  • Adding tuples using defaultdict()

Method 1: Explicit Declaration of a List

We can explicitly declare a list containing multiple elements and assign it to a key. The detailed process involves initializing the keys with lists containing single values, then updating the lists with assignment operator.

Syntax

dictionary_name = {'key': ['first_value'],
dictionary_name[‘key'] += ['value_added']

Here we are adding values to the list which has been originally mapped as the value to a particular key of a dictionary (initialized in the first statement). Elements can be added to a list by simply using the assignment operator, similar to appending strings together, which is shown in the second statement.

Algorithm

Step 1 − Create a dictionary and initialize keys with single-element lists

Step 2 − Add newer elements to the lists connected to keys to which multiple values are to be mapped

Step 3 − Print or perform further necessary operations on the data

Example

shop = {'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk']}
print(f'shop list: \n{shop}')
shop['available'] += ['fish']
shop['available'] += ['another fish', 'and another fish']
print(f'shop list: \n{shop}') 

Output

shop list:
{'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk']}
shop list:
{'available': ['bread', 'fish', 'another fish', 'and another fish'], 'not available': ['eggs'], 'excess': ['milk']}

Method 2: Adding Values with extend() Function

The extend() method can be used exactly similar to the assignment operator, to add values to a particular key element. Instead of using ‘+=’ with the key, we add the .extend() function to the key, which adds a value to the list mapped to the key.

Syntax

dictionary_name['key'].extend(['new_listvalue'])

Here we can see, the extend() method is called on the dictionary for the particular key value. The extend() function takes only a single argument, hence only a single value can be added to the list at a time. If we add a comma-separated list of values, the interpreter will return a TypeError.

Algorithm

Step 1 − Create the dictionary

Step 2 − Initialize keys with single-valued lists

Step 3 − Extend the lists and add more values to a particular key element

Example

shop = {'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk']}
print(f'shop list: \n{shop}')
shop['available'].extend(['fish'])
shop['available'].extend(['another fish', 'and another fish'])
print(f'shop list: \n{shop}')

Output

shop list:
{'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk']}
shop list:
{'available': ['bread', 'fish', 'another fish', 'and another fish'], 'not available': ['eggs'], 'excess': ['milk']} 

Method 3: Adding Sublists to a List Using append() Function

Unlike the previously used assignment operator or extend() methods, the append() method acts a bit differently. This function,instead of adding values to an existing mapped list in a dictionary, creates sublists in that mapped list and stores the value in them. Thus, it can be considered as an exponential approach in which the dimension of lists increases after each insertion operation. The usability of this method depends on whether our current application requires this much depth, as it also comes with a downside, that complexity increases rapidly.

Syntax

dictionary_name['key'].append(['value1'])

The syntax is similar to the extend() method, and that is why these two methods may appear pretty similar in working at first. The append() function is called on the dictionary key required, and the value in the list is passed. Here also only a single argument can be passed to the append() function, if we pass a comma-separated list of sublists, it will show a TypeError.

Algorithm

Step 1 − Create a dictionary

Step 2 − Initialize keys with single-valued lists

Step 3 − Call the append() function to pass sublists containing values to a particular key

Step 4 − For accessing the individual sublists, we use the indices of the main list and corresponding sublists

Example

shop = {'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk']}
print(f'shop list: \n{shop}')
shop['available'].append(['fish'])
print(f'shop list: \n{shop}')
print(shop['available'][1][0])

Output

shop list: 
{'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk']}
shop list: 
{'available': ['bread', ['fish']], 'not available': ['eggs'], 'excess': ['milk']}
fish

Method 4: Adding Values Using the setdefault() Method

In this method, we use the setdefault() method to add multiple values to a key. If there is a particular key already present in the dictionary, then this function adds the values passed to the key. Otherwise, a new key is created containing the new value as default. Then we can use methods like extend() to add newer values to the existing values of a particular key.

Syntax

shop.setdefault('restocked', []).extend(['apples', 'oranges'])

Here we pass two arguments to the setdefault() function as we do not know whether the specified key is already present in the dictionary. If we are sure that the key is present then the second argument (the blank list) can be ignored. We then add the values which we will add in the list paired to the key, using the extend() function.

Algorithm

Step 1 − Create a dictionary

Step 2 − Initialize keys with single-valued lists

Step 3 − Call the setdefault() function to pass new values to a particular key, whether it is already present or not

Step 4 − Add more values using the extend() function

Example

shop = {'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk']}
print(f'shop list: \n{shop}')
shop.setdefault('restocked', []).extend(['apples', 'oranges'])
print(f'shop list: \n{shop}') 

Output

shop list:
{'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk']}
shop list:
{'available': ['bread'], 'not available': ['eggs'], 'excess': ['milk'], 'restocked': ['apples', 'oranges']} 

Method 5: Adding Tuples Using defaultdict()

This is the only method here that we are going to discuss which works with tuples instead of lists. As tuples are immutable, we cannot push values separately into a tuple linked to a key. Here the defaultdict() function comes to the rescue, which is a sub-class of the dict class. We use tuples to assign key-value pairs, and if the key already exists, the value is added to the existing list.

Syntax

shop_dict = defaultdict(list)

Here, the defaultdict() function converts the tuples into key-value pairs and initializes a dictionary with them. Then multiple values are added using any of the methods used above.

Algorithm

Step 1 − Create a dictionary and import defaultdict() class

Step 2 − Initialize key-value pairs with tuples using the defaultdict() function

Step 3 − Add more values using the extend() function or other methods described above

Example

from collections import defaultdict
shop=[("shop1","bread"),("shop2","milk"),("shop3","chips")]
shop_dict = defaultdict(list)
for key, value in shop:
   {shop_dict[key].append(value)} 
shop_dict['shop1'].extend(['coke','biscuits'])
print(f'shop list: \n'+str(dict(shop_dict))) 

Output

shop list: 
{'shop1': ['bread', 'coke', 'biscuits'], 'shop2': ['milk'], 'shop3': ['chips']} 

Conclusion

Thus we have inferred in this article that a single key can have multiple values in a dictionary in Python. We have also gone through the common methods of adding multiple values to a single key in a Python dictionary. There are several more methods to add values to a key, which can be explored later in detail. Hope it was a great learning experience going through this article!

Updated on: 24-Mar-2023

27K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements