- Append to Dictionary in Python
- Overview of dict.update()
- Frequently Asked:
- Add / Append a new key-value pair to a dictionary in Python
- Add / Append a new key value pair to a dictionary using update() function
- Add / Append a new key-value pair to a dictionary using [] operator
- Add to python dictionary if key does not exist
- Add / Append values to an existing key to a dictionary in python
- Updating the value of existing key in a dictionary
- Append multiple key value pair in dictionary
- Adding a list of tuples (key-value pairs) in the dictionary
- Adding a dictionary to another dictionary
- Add items to a dictionary in a loop
- Add list as a value to a dictionary in python
- Related posts:
- Share your love
- 6 thoughts on “Append to Dictionary in Python”
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- 6 Ways to Add Values to Dictionary in Python
- Method 1: Using the dictionary.update() method
- Example
- Method 2: Assigning a value to a new key in Dictionary
- Example
- Method 3: Using the merge operator ( | )
- Example
- Method 4: Using the update operator ( |= )
- Example
- Method 5: Creating a custom function
- Example
- Method 6: Using __setitem__()
- Example
Append to Dictionary in Python
This article will discuss how to add or append new key-value pairs to a dictionary or update existing keys’ values.
Table of Contents
We can add/append key-value pairs to a dictionary in python either by using the [] operator or the update function. Let’s first have an overview of the update() function,
Overview of dict.update()
Python dictionary provides a member function update() to add a new key-value pair to the diction or to update the value of a key i.e.
Frequently Asked:
- sequence: An iterable sequence of key-value pairs.
- It can be a list of tuples or another dictionary of key-value pairs.
For each key-value pair in the sequence, it will add the given key-value pair in the dictionary and if key already exists, it will update its value. We can use this function to add new key-value pairs in the dictionary or updating the existing ones.
Checkout complete tutorial on dict.update() function.
Add / Append a new key-value pair to a dictionary in Python
We can add a new key-value pair to a dictionary either using the update() function or [] operator. Let’s look at them one by one,
Add / Append a new key value pair to a dictionary using update() function
To add a new key-value in the dictionary, we can wrap the pair in a new dictionary and pass it to the update() function as an argument,
# Dictionary of strings and ints word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 43 ># Adding a new key value pair word_freq.update() print(word_freq)
It added the new key-value pair in the dictionary. If the key already existed in the dictionary, then it would have updated its value.
If the key is a string you can directly add without curly braces i.e.# Adding a new key value pair word_freq.update(after=10)
Add / Append a new key-value pair to a dictionary using [] operator
We add a new key and value to the dictionary by passing the key in the subscript operator ( [] ) and then assigning value to it. For example,
# Dictionary of strings and ints word_freq = < "Hello": 56, "at": 23, "test": 43, "this": 43 ># Add new key and value pair to dictionary word_freq['how'] = 9 print(word_freq)
It added a new key ‘how’ to the dictionary with value 9.
Learn more about Python Dictionaries
Add to python dictionary if key does not exist
Both the subscript operator [] and update() function works in the same way. If the key already exists in the dictionary, then these will update its value. But sometimes we don’t want to update the value of an existing key. We want to add a new key-value pair to the dictionary, only if the key does not exist.
We have created a function that will add the key-value pair to the dictionary only if the key does not exist in the dictionary. Check out this example,
def add_if_key_not_exist(dict_obj, key, value): """ Add new key-value pair to dictionary only if key does not exist in dictionary. """ if key not in dict_obj: word_freq.update() # Dictionary of strings and ints word_freq = add_if_key_not_exist(word_freq, 'at', 20) print(word_freq)
As key ‘at’ already exists in the dictionary, therefore this function did not added the key-value pair to the dictionary,
Now let’s call this function with a new pair,
add_if_key_not_exist(word_freq, 'how', 23) print(word_freq)
As key ‘how’ was not present in the dictionary, so this function added the key-value pair to the dictionary.
Add / Append values to an existing key to a dictionary in python
Suppose you don’t want to replace the value of an existing key in the dictionary. Instead, we want to append a new value to the current values of a key. Let’s see how to do that,
def append_value(dict_obj, key, value): # Check if key exist in dict or not if key in dict_obj: # Key exist in dict. # Check if type of value of key is list or not if not isinstance(dict_objPython add new values to dictionary, list): # If type is not list then make it list dict_objPython add new values to dictionary = [dict_objPython add new values to dictionary] # Append the value in list dict_objPython add new values to dictionary.append(value) else: # As key is not in dict, # so, add key-value pair dict_objPython add new values to dictionary = value # Dictionary of strings and ints word_freq = append_value(word_freq, 'at', 21) print(word_freq)
It added a new value, 21, to the existing values of key ‘at’.
How did it work?
We will check if the key already exists in the dictionary or not,
- If the key does not exist, then add the new key-value pair.
- If the key already exists, then check if its value is of type list or not,
- If its value is list object and then add new value to it.
- If the existing value is not a list, then add the current value to a new list and then append the new value to the list. Then replace the value of the existing key with the new list.
Let’s check out some other examples of appending a new value to the existing values of a key in a dictionary,
append_value(word_freq, 'at', 22) print(word_freq)
append_value(word_freq, 'how', 33) print(word_freq)
Updating the value of existing key in a dictionary
If we call the update() function with a key/value and key already exists in the dictionary, then its value will be updated by the new value, i.e., Key ‘Hello’ already exist in the dictionary,
# Dictionary of strings and ints word_freq = # Updating existing key's value word_freq.update() print(word_freq)
The value of the key ‘hello’ is updated to 99.
Check out another example,
word_freq['Hello'] = 101 print(word_freq)
Append multiple key value pair in dictionary
As update() accepts an iterable sequence of key-value pairs, so we can pass a dictionary or list of tuples of new key-value pairs to update(). It will all add the given key-value pairs in the dictionary; if any key already exists then, it will update its value.
Adding a list of tuples (key-value pairs) in the dictionary
# Dictionary of strings and ints word_freq = # List of tuples new_pairs = [ ('where', 4) , ('who', 5) , ('why', 6) , ('before' , 20)] word_freq.update(new_pairs) print(word_freq)
Adding a dictionary to another dictionary
Suppose we have two dictionaries dict1 and dict2. Let’s add the contents of dict2 in dict1 i.e.
# Two dictionaries dict1 = < "Hello": 56, "at": 23, "test": 43, "this": 43 >dict2 = # Adding elements from dict2 to dict1 dict1.update( dict2 ) print(dict1)
Add items to a dictionary in a loop
Suppose we have a list of keys, and we want to add these keys to the dictionary with value 1 to n. We can do that by adding items to a dictionary in a loop,
word_freq = new_keys = ['how', 'why', 'what', 'where'] i = 1 for key in new_keys: word_freqPython add new values to dictionary = i i += 1 print(word_freq)
Add list as a value to a dictionary in python
You can add a list as a value to a key in the dictionary,
word_freq = word_freq.update() print(word_freq) word_freq['what'] = [1, 2, 3] print(word_freq)
We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.
Related posts:
Share your love
6 thoughts on “Append to Dictionary in Python”
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
6 Ways to Add Values to Dictionary in Python
Here are 6 methods to add values to a dictionary in Python:
- Using “dict.update()” method
- Assigning a value to a new key.
- For Python 3.9+, use the merge operator(|).
- For Python 3.9+, use the update operator(|=).
- Creating a custom function.
- Using the “__setitem__()” method (Not recommended).
Method 1: Using the dictionary.update() method
To add values to a dictionary in Python, you can use the “dictionary.update()“ method. This method can also replace the value of any existing key or append single or multiple new values to the keys.
Example
init_dict = print(init_dict) new_values = print("Adding multiple values to a dict") init_dict.update(new_values) print(init_dict)
Adding multiple values to a dict
Method 2: Assigning a value to a new key in Dictionary
To assign a value to a new key in a dictionary, you can use the assignment operator (=). Create an empty dictionary in Python, use the < >, and assign the values to the dictionary using the assignment operator.
Example
You can use one of the following approaches to append initial values to a dictionary.
init_dict = print(init_dict) init_dict_second = dict(a=11, b=21, c=19) print(init_dict_second) init_dict_third = print(init_dict_third)
You can see that we have seen three different approaches to defining a dictionary with initial values.
Now, let’s append values to a dictionary by assigning a value to that key. The new value has a key name, “d”, and is 46.
This means we are appending a new key-value pair to an existing dictionary.
init_dict = print(init_dict) print("Add new value to a dict") init_dict['d'] = 46 print(init_dict)
Method 3: Using the merge operator ( | )
Python 3.9 comes with a merge operator that helps us merge the dictionaries. The Merge (|) operator has been added to a built-in dict class.
You use the merge operator to combine two dictionaries or, in other words, create a new dictionary by adding new key values to the existing dictionary.
Example
init_dict = print(init_dict) new_values = print("Merging dictionary values using merge operator") final_dict = init_dict | new_values print(final_dict)
Adding multiple values to a dict
You can see that we got the combined dictionary with updated values.
Method 4: Using the update operator ( |= )
Python 3.9 comes with one more operator called the update operator. The update (|=) operator returns the left operand merged with the right operand.
Example
init_dict = print(init_dict) new_values = print("Adding dictionary values using update operator") init_dict |= new_values print(init_dict)
Updating dictionary values using update operator
We add multiple values to the existing dictionary using the |= operator, which won’t work below the Python 3.9 version.
Method 5: Creating a custom function
To create a custom function that will do the job of adding the values to the dictionary, you can do that.
Example
class create_dict(dict): def __init__(self): self = dict() def add(self, key, value): selfPython add new values to dictionary = value dct = create_dict() dct.add('a', 19) dct.add('b', 21) print(dct)
Method 6: Using __setitem__()
Another way to add new values to a dict you shouldn’t use is the __setitem__ method. The main reason behind this is that the methods that start with __ are private in Python. So it is a good practice not to use the private method of Python.
Example
dct = <> dct.__setitem__('a', 21) print(dct)