Abstract: You can easily add multiple values to a key in a Python dictionary using different methods.
- We’ll explain each of the possible methods in detail, and also show you how you can update and delete multiple values.
- Finally, we’ll show you how to add multiple values to a python dictionary by creating a function using one of the methods outlined.
General Idea: In Python, if we want a dictionary to have multiple values for a single key, we need to store these values in their own container within the dictionary.
To do so, we need to use a container as a value and add our multiple values to that container.
Common containers are lists, tuples, and sets. The most suited kind for adding multiple values is a list, which is what we will focus on here.
Feel free to watch me explain these methods in the following video guide:
Lists as Values – Assigning Multiple Values to a Key
Using lists as containers for multiple values is the easiest way to assign multiple values to any key. Let’s quickly recap and compare the properties of lists and dictionaries:
Lists
Lists are inside square brackets []
. They are mutable and ordered. The values are comma-separated and indexed by position.
Some properties of lists:
- mutable
- ordered
- comma-separated values
- inside square brackets
- indexed by position
Here’s a simple list with three values. Each of these values is indexed by its zero-based position, meaning the first value is 0, the second is 1, and so on.
my_list = ['terrier', 'cat', 'parrot']
Dictionaries are inside curly braces {}
. They are also mutable and ordered. Keys are paired with their values with a colon. Key-value pairs are comma-separated and indexed by their key.
Dictionaries
- mutable
- ordered
- comma-separated key-value pairs
- separated by a colon
- inside curly braces
- indexed by key
Here’s a simple dictionary with three values. Each of these values is indexed by its key.
my_dict = {'available': 'terrier', 'not available': 'cat', 'dead': 'parrot'}
If we want to access a value of a list, we call the indexed position. If we want to access a value of a dictionary, we call it’s key. Let’s call the position of our first list-value ‘terrier’.
my_list = ['terrier', cat, 'parrot'] print(my_list[0])
Let’s call our dictionary-value 'terrier'
, this time by calling the corresponding key.
my_dict = {'available': 'terrier', 'not available': 'cat', 'dead': 'parrot'} print(my_dict['available'])
Adding Multiple Values to a Dictionary Key Directly
The first and very simple way to add multiple values to a dictionary key is by adding a list directly in place of a value when creating the dictionary. This dictionary contains three single-value key-value pairs:
my_dict = {'available': 'terrier', 'not available': 'cat', 'dead': 'parrot'}
Now let’s change the first key-value pair by adding square brackets around the value 'terrier'
. That’s it. This dictionary now contains single value key-value pairs, of which the first value is a list. That list itself contains one value: 'terrier'
my_dict = {'available': ['terrier'], 'not available': 'cat', 'dead': 'parrot'}
If you are not sure about a value yet, but you know which key you’d like to use, it’s not a problem. You can just add an empty list and fill it at a later time.
my_dict = {'available': [], 'not available': 'cat', 'dead': 'parrot'}
So, now that we have set up our list, we can fill it with as many values as we like. Let’s add a second dog to our available list.
my_dict = {'available': ['terrier', 'mutt'], 'not available': 'cat', 'dead': 'parrot'}
Now let’s access all of the values for one key by calling the key of the key-value pair we want to see. In this case, the key 'available'
.
print(my_dict['available'])
This returns the list of the values we set for this key.
If we want to access a single value from a key-multiple-value pair, we can do that by accessing the indexed position of the value.
print(my_dict['available'][0])
Having a zero-based index, 0 shows us the first value of our key-multiple-value pair. Great!
Ok, now we’re warmed up, let’s look at the options we have for existing dictionaries. Our first method to add multiple values to a dictionary key is the assignment operator +=
.
Method 1: Adding Multiple Values to a Dictionary using Operators
We can use the assignment operator +=
to add values to a specific key in the same way we use it to add values to variables.
word1 = 'sleeping ' word1 += 'parrot' print(word1)
Let’s create a dictionary with our single values already stored as lists:
petshop = {'available': ['terrier'], 'not available': ['cat'], 'convertible': ['terrier'], 'dead': ['parrot']} print(f'petshop list: \n{petshop}')
Our print shows our dictionary with each of the values already inside a list. If we want to add another value to a key, we simply add it as a list – in square brackets – to our key of choice. In our case, let’s add a fish to the available pets:
petshop['available'] += ['fish']
Check the result and see, we have added a second value to an existing key. We can add as many values to our list as we like. Make sure to separate each value with a comma:
petshop['available'] += ['another fish', 'and another fish']
If you are already familiar with extend and append-methods, please note that the +=
assignment operator works like the extend-method, not like the append-method. We’ll cover both those methods in more detail later.
Now, let’s move on to our second method: extend()
.
Method 2: Adding Multiple Values to a Dictionary using extend()
The second method we can use to add values to a key is the extend()
method. The extend()
method works the same way as the +=
assignment operator we just covered. Here’s our previous petshop dictionary with single-values stored as lists:
petshop = {'available': ['terrier'], 'not available': ['cat'], 'convertible': ['terrier'], 'dead': ['parrot']}
Instead of using the +=
operator, we add .extend()
to our targeted dictionary key and insert the value we want to add to the key as a list inside of extend
‘s parentheses.
petshop['available'].extend(['fish'])
Extending works like the +=
operator – we extend the list of values.
petshop['available'].extend(['another fish', 'and another fish'])
The extend-method only takes one argument, in our case either a single value or a single list. If we try to add a second list separated by a comma we’ll receive a TypeError
.
Let’s move on to our next method, append()
.
Method 3: Adding Multiple Values to a Dictionary using append()
The third method we use to add multiple values to a key is the append()
method.
The append()
method works differently than the +=
assignment operator and extend()
method, which are similar to each other. At first glance it’s easy. We just change extend
to append
.
petshop['available'].append(['fish'])
But when we look at our petshop dictionary with an appended value, there’s an important difference. Where extend()
added the new value to the existing value list within the dictionary, append()
adds a new list within the existing value list.
The downside is that we are creating sublists within lists. The upside is that your next project may need that kind of depth. Maybe.
petshop['available'].append(['another fish', 'and another fish'])
Just like the extend()
method, the append-method only takes one argument, in our case one list. If we try to add a second list separated by a comma we’ll receive a TypeError
.
How do we access the values inside a list inside of the values?
Remember, we access a single value for key-multiple-value pairs by accessing the indexed position:
print(petshop['available'][0])
So, to access the list of fish we just appended we need to choose the third value of our petshop
dictionary.
print(petshop['available'][2])
And if we want to access values from within a list within a key-multiple-value pair, we use the same logic:
print(petshop['available'][2][0])
First, we access the indexed position of the fish
list, then the indexed position within that list – Inception-style depth here π
On a side note, if you happen to use sets instead of lists within your multi-value dictionary, you will use the add()
method instead of the append()
method.
Method 4: Adding Multiple Values to a Dictionary using setdefault()
The fourth method we can use for adding multiple values to a key is the setdefault()
method. The setdefault()
method will set the value to the default value if it finds a matching key. If it doesn’t it will create a new key adding the new value as default.
π‘ Note: Any key that is not in the dictionary will automatically be added. If the key is already in the dictionary, the value will be appended to the end.
Using our petshop
dictionary again, this is how we use setdefault
.
petshop = {'available': ['terrier'], 'not available': ['cat'], 'convertible': ['terrier'], 'dead': ['parrot']} print(f'petshop list: \n{petshop}')
Using the setdefault()
method in combination with extend()
adds the new values to the value-list of the specified key. The method takes two parameters, of which the second can be omitted if the key already exists in the dictionary.
If we’re not sure if the key exists and if we want to add multiple values, we add an empty list as the second parameter.
petshop.setdefault('dead', []).extend(['duck', 'frog'])
If we’re sure that our key exists, we can omit the second parameter.
petshop.setdefault('dead').extend(['duck', 'frog'])
If we’re sure our key doesn’t exist, we need to add an empty list as our second parameter.
petshop.setdefault('allegedly dead', []).extend(['parrot', 'mouse'])
If we use the append()
method here, instead of the extend()
method, the new values will also be added to a new list inside of the existing value list.
Method 5: Adding Multiple Values to a Dictionary using defaultdict()
The fifth method we can use for adding multiple values to a key is the defaultdict()
method.
At some point in your career, you will come across a list of tuples. Tuples are immutable, meaning elements can’t be added, removed or reordered.
So, if you have a list of tuples you can’t just take one value and add it to an existing key. This is where the defaultdict()
method is your best friend. Let’s take a look at our tuplified list from previous examples:
petshop = [('available', 'terrier'), ('available', 'another terrier'), ('available', 'a third terrier'), ('not available', 'cat'), ('convertible', 'terrier'), ('dead', 'parrot')]
The key-value pairs in this list of tuples are separated by commas. We have three different tuples with the same key-value. It would be great if we could combine the three into a single key with multiple values. Fortunately, that’s exactly what we can do using the defaultdict
module.
The defaultdict
class is a sub-class of the dict
class and must be imported from the collections
module before it can be used. We can use defaultdict
to convert a sequence of tuples to a dictionary:
from collections import defaultdict
We start by creating a variable for our new dictionary and tell it that we will be using the defaultdict
module that we just imported. Then we’ll create a simple for loop telling the interpreter to assign the key to the first element in each tuple, and the value to the second element.
petshop_dict = defaultdict(list) for key, value in petshop: petshop_dict[key].append(value)
Whenever a key already exists the value is appended to the existing value.
Once our tuple is converted to a dictionary with key-value pairs, we can use any of the methods we have covered so far to add multiple values to keys. If our tuple already contained multiple values for the same keys, then defaultdict will automatically store them inside of a multiple-value-list.
Method 6: Updating Multiple Values of a Dictionary using update()
Now we’ve covered the most common ways to add multiple values to a Python dictionary. Let’s sidestep a little and see how we can update the multiple values we have added.
To use this method within our dictionary, we will use the dict.fromkeys()
method to create a new dictionary with the updated values. The update()
method replaces current values with updated values.
π Warning – update means deleting the existing value and adding one or more new values. The old values will be replaced = deleted!
Here’s our petshop
again. Our terrier is still available.
petshop = {'available': ['terrier'], 'not available': ['cat'], 'convertible': ['terrier'], 'dead': ['parrot']} print(f'petshop list: \n{petshop}')
Let’s add two values to our 'available'
-key, an updated terrier, and an updated hamster.
petshop.update(dict.fromkeys(['available'], ['updated terrier', 'updated hamster']))
As you can see, the new values have been added and our old terrier has left the shop forever.
Update multiple values of multiple keys simultaneously
A useful function of the update()
method is, that you can update more than one key at a time, by comma-separating the keys. This will replace any values within the given keys with our new values.
petshop.update(dict.fromkeys(['available', 'dead'], ['updated terrier', 'updated parrot']))
If the key doesn’t exist in the dictionary, it will be added and updated with the values given.
petshop.update(dict.fromkeys(['allegedly dead'], ['updated parrot']))
Method 7: Deleting Multiple Values of a Dictionary using del
With the del
keyword we can delete keys and multiple values. Using our petshop dictionary, it’s easy to target keys and values for deletion.
petshop = {'available': ['terrier', 'another terrier', 'a third terrier'], 'not available': ['cat', 'another cat', 'a third cat'], 'convertible': ['terrier'], 'dead': ['parrot', 'another parrot', 'a sleeping parrot'], 'allegedly dead': ['parrot', 'a sleeping parrot']} print(f'petshop list: \n{petshop}')
Looking at our petshop
dictionary, we can already see we should delete the whole key-value pair ‘dead’ – as we know that our parrot is just sleeping and not really dead. So, let’s remove it.
del petshop['dead']
Great, no more dead pets here.
To delete a single value from a key, we can call the index position. Python uses zero-based indexing, so 0 for the first value, 1 for the second, etc. Letβs delete the first terrier.
del petshop['available'][0]
To delete multiple values from a key, we can use the range syntax (start
, stop
, step
) separated by colons. See this article for a detailed guide on slicing:
I’ve added some more terriers to our petshop
dictionary to clarify our steps. I’ve named them according to their index position from 0 – 9:
petshop = {'available': ['terrier 0', 'terrier 1', 'terrier 2', 'terrier 3', 'terrier 4', 'terrier 5', 'terrier 6', 'terrier 7', 'terrier 8', 'terrier 9'], 'not available': ['cat', 'another cat', 'a third cat'], 'convertible': ['terrier'], 'dead': ['parrot', 'another parrot', 'a sleeping parrot'], 'allegedly dead': ['parrot', 'a sleeping parrot']}
Now, let’s delete terriers 3 and 6. To do that, we start our deletion at position 3, which will be included and end at position 7, which will be excluded. And we want to delete every third step, so 3:7:3
– don’t forget, start
is inclusive and stop
is exclusive.
del petshop['available'][3:7:3]
Great, terriers 3 and 6 found a new home.
Method 8: Creating a Function to add Multiple Values to a Dictionary using def
Let’s wrap up what we have learned by creating a simple function that will add multiple values to our dictionary using the extend()
method.
One final time, let’s look at our petshop dictionary.
petshop = {'available': ['terrier'], 'not available': ['cat'], 'convertible': ['terrier'], 'dead': ['parrot']}
Our function will make it easier to add multiple values to our dictionary.
First, we define our function. Our function will accept 3 parameters: petshop
(our dictionary), status
(our keys) and pet
(our values).
If our key is not in the petshop
we will create a new one containing an empty list for our new pet.
Then we will add the new pet to whichever key we chose (existing or new) via extend()
method.
And finally, we’ll return our dictionary with the new value.
def abandoned_pets(petshop, status, pet): if status not in petshop: petshop[status] = list() petshop[status].extend(pet) return petshop
Because we are using lists for our multiple values, we can pass a list containing as many values as we like as our pet parameter.
petshop = abandoned_pets(petshop, 'available', ['another terrier', 'and another terrier', 'aaand a third terrier']) print(f'petshop list: \n{petshop}')
Summary – Many Ways to Add Multiple Values to a Key in a Python Dictionary
There are many ways you can add multiple values to a key in a Python dictionary.
We covered how you can achieve this with different methods.
We explained each of the methods in detail, and also showed you how you can update and delete multiple values.
Finally, we showed you an example of how to add multiple values to a python dictionary using one of the methods in a function.
Now you know for sure:
Yes, it is possible to add multiple values to a key in a python dictionary!