Python dictionary allows you to store values in key-value pairs.
You can add multiple values to the same key in the dictionary in Python using yourdict.setdefault(‘numbers’, [ ]).append(4) statement.
Basic Example
yourdict = {
'numbers' : [1 ,2,3],
'small_letters' : ['a', 'b']
}
yourdict.setdefault('numbers’, [4]).append(4)
print(yourdict)
The value type of the dictionary key must be a container such as a list, set or tuple to add multiple values to the same key.
Creating a Dictionary With Multiple Values For a Key
This section teaches you how to create a dictionary with a list of values for a single key.
The value type of each key is a list
that can contain more than one value in a single object.
Code
yourdict = {
'numbers' : [1 ,2,3],
'small_letters' : ['a', 'b']
}
print(yourdict)
Output
{'numbers': [1, 2, 3], 'small_letters': ['a', 'b']}
Using SetDefault
This section teaches you how to add a value to an existing key in the dictionary using the setdefault() method.
The setdefault()
method works in the following way:
- If the
key
doesn’t exist, it adds the key to the dictionary - If the
key
exists already, it returns the value of the key
To add multiple keys using the setdefault()
method
- Get the existing
list
object of the key. - Append a value to the existing list using the
list.append()
method. - If the key is not existing in the dictionary, then add the key and value as a list to the dictionary
Code
yourdict = {
'numbers' : [1 ,2,3],
'small_letters' : ['a', 'b']
}
yourdict.setdefault('numbers’, [4]).append(4)
print(yourdict)
Output
The value four is added to the key
– numbers.
{'numbers': [1, 2, 3, 4], 'small_letters': ['a', 'b']}
Another Example
The following code demonstrates what happens while using the setdefault()
method when the key already exists in the dictionary.
It returns the value of the existing key
, and nothing else changes in the dictionary.
yourdict = {
'numbers' : [1 ,2,3],
'letters' : ['a', 'b']
}
yourdict.setdefault('special_chars', [".",","])
print(yourdict)
yourdict.setdefault('special_chars', [".",",", "#"])
Output
The hash symbol #
is not added to the special_chars key
because the key was already existing in the dictionary.
{'numbers': [1, 2, 3], 'letters': ['a', 'b'], 'special_chars': ['.', ',']}
['.', ',']
Using DefaultDict
This section explains how to use the DefaultDict
to add multiple values to the same key in the dictionary.
The DefaultDict
class allows you to specify a default value for a key when the value is not specified.
For example:- If you add a key to the dictionary and don’t add any value to the key, then the default callable value specified during the dictionary creation will be used.
To add multiple values to the same key in the dictionary,
- initialize the defaultdict with a list as
defaultdict(list)
. - Append values to the existing list of a key using the
append()
method. You can use thelist.extend()
method to add multiple items at once.
Code
from collections import defaultdict
yourdict = defaultdict(list)
yourdict["numbers"].append(1)
yourdict["numbers"].append(2)
yourdict["letters"].append('a')
yourdict["letters"].append('b')
yourdict["chars"]
yourdict
Output
- Append method appended values to the existing key.
- When the non-existing
key
is passed, it is added with an empty list as a value.
defaultdict(list, {'numbers': [1, 2], 'letters': ['a', 'b'], 'chars': []})
Using Dict and If Statement
This section teaches you how to use the dict
and if
statements to add multiple values.
To use this method, the existing dictionary key must have the value of the type list
object.
- Check if the
key
is already existing in the dictionary. If yes, then append the value to the list - If the key doesn’t exist, assign the new list of values to the new key.
Code
yourdict = dict()
if "numbers" in yourdict:
yourdict["numbers"].append(2)
else:
yourdict["numbers"] = [2]
print(yourdict)
Output
{'numbers': [2]}
Add List of Values To Dictionary Keys
This section teaches you how to add a list of values to an existing key.
To use this method, the key of the dictionary must have a value of type list
- Use the
setdefault()
method - Use the the
list.extend()
method to add more values to an existing list at once.
To know the differences between list.append()
and list.extend()
method, read:- Python List Append Vs Extend – Differences Explained
Code
yourdict = {
'numbers' : [1 ,2,3],
'small_letters' : ['a', 'b']
}
yourdict.setdefault('small_letters').extend(['c','d','e'])
print(yourdict)
Output
{'numbers': [1, 2, 3], 'small_letters': ['a', 'b', 'c', 'd', 'e']}