How To Add to a Dictionary in Python?

How To Add to a Dictionary in Python?

The dictionary is a built-in data type in Python, serving as a collection of key-value pairs. Unlike lists or tuples, dictionaries are mutable, allowing for modifications. However, dictionary keys are immutable and must maintain uniqueness within the dictionary. Although there isn’t a dedicated “add” method, multiple approaches exist for incorporating new elements or modifying existing ones in a dictionary. This article explores techniques like the assignment operator, the update() method, and the merging and updating dictionary operators, which enable adding and modifying entries within Python dictionaries.

Adding to a Dictionary Using the = Assignment Operator

The = assignment operator can be used to introduce a fresh key into a dictionary:

Example:


my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3
print(my_dict)

Output:

 {'a': 1, 'b': 2, 'c': 3}

In this example, the key ‘c’ is appended to the dictionary my_dict with the corresponding value 3 using the = assignment operator. The resulting dictionary will include the new key-value pair: {‘a’: 1, ‘b’: 2, ‘c’: 3}.

If a key already exists in the dictionary, using the assignment operator updates or overwrites the value.

The following example illustrates how to create a new dictionary and subsequently utilize the assignment operator (=) to update values and add key-value pairs:

Example:

dict_example = {'a': 1, 'b': 2}
print("original dictionary: ", dict_example)
dict_example['a'] = 100  # existing key, overwrite
dict_example['c'] = 3  # new key, add
dict_example['d'] = 4  # new key, add 
print("updated dictionary: ", dict_example)

Output:

original dictionary:  {'a': 1, 'b': 2}
updated dictionary:  {'a': 100, 'b': 2, 'c': 3, 'd': 4}

The output reveals that the new value overwrites the value of ‘a’, the value of ‘b’ remains unchanged, and new key-value pairs are introduced for ‘c’ and ‘d’.

Adding to a Dictionary Without Overwriting Values:

Using the = assignment operator replaces existing fundamental values with new ones. If you know your program could contain duplicate keys and wish to avoid overwriting the original values, you can selectively add values using an if statement.

Continuing with the example from the preceding section, you can use if statements to add only new key-value pairs to the dictionary:

dict_example = {'a': 1, 'b': 2}
print("original dictionary: ", dict_example)
dict_example['a'] = 100  # existing key, overwrite
dict_example['c'] = 3  # new key, add
dict_example['d'] = 4  # new key, add 
print("updated dictionary: ", dict_example)
# add the following if statements
if 'c' not in dict_example.keys():
    dict_example['c'] = 300
if 'e' not in dict_example.keys():
    dict_example['e'] = 5
print("conditionally updated dictionary: ", dict_example)

Save $100 in the next
5:00 minutes?

Register Here

Output:

original dictionary:  {'a': 1, 'b': 2}
updated dictionary:  {'a': 100, 'b': 2, 'c': 3, 'd': 4}
conditionally updated dictionary:  {'a': 100, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

The output shows that, because of the if condition, the value of c didn’t change when the dictionary was conditionally updated.

Adding to a Dictionary Using the update() Method:

You can use the update() method to extend a dictionary by adding another dictionary or an iterable containing key-value pairs. The update() method will overwrite the values of existing keys with the new ones.

The following example demonstrates how to create a new dictionary, use the update() method to add a new key-value pair and a new dictionary, and print each result:

site = {'Website':'example.com', 'Tutorial':'How To Add to a Python Dictionary'}
print("original dictionary: ", site)
# update the dictionary with the author key-value pair
site.update({'Author':'sandy'})
print("updated with Author: ", site)
# create a new dictionary
guests = {'Guest1':'Sammy', 'Guest2':'Xray'}
# update the original dictionary with the new dictionary
site.update(guests)
print("updated with new dictionary: ", site)

Output:

original dictionary:  {'Website': 'example.com', 'Tutorial': 'How To Add to a Python Dictionary'}
updated with Author:  {'Website': 'example.com', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'sandy'}
updated with new dictionary:  {'Website': 'example.com', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'sandy', 'Guest1': 'Sammy', 'Guest2': 'Xray'}

The output shows that the first update adds a new key-value pair, and the second update adds the key-value pairs from the guest dictionary to the site dictionary. Note that if your update to a dictionary includes an existing key, the update overwrites the old value.

Adding to a Dictionary Using the Merge | Operator:

You can utilize the dictionary merge | operator, represented by the pipe character, to combine two dictionaries and generate a new dictionary object.

The following example demonstrates how to create two dictionaries and use the merge operator to create a new dictionary that contains the key-value pairs from both:

site = {'Website':'example.com', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'sandy'}
guests = {'Guest1':'Sammy', 'Guest2':'Xray'}
new_site = site | guests
print("site: ", site)
print("guests: ", guests)
print("new_site: ", new_site)

Output:

site:  {'Website': 'example.com', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'sandy'}
guests:  {'Guest1': 'Sammy', 'Guest2': 'Xray'}
new_site:  {'Website': 'example.com', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'sandy', 'Guest1': 'Sammy', 'Guest2': 'Xray'}

The merging of the two dictionaries resulted in a new dictionary object containing key-value pairs from both sources.

If a key exists in both dictionaries, the value from the second dictionary, or right operand, is the value taken. In the following example code, both dictionaries have a key called b:

dict1 = {'a':'one', 'b':'two'}
dict2 = {'b':'letter two', 'c':'letter three'}
dict3 = dict1 | dict2
print{"dict3: ", dict3}

output:

dict3:  {'a': 'one', 'b': 'letter two', 'c': 'letter three'}

The value associated with the key “b” was replaced by the value from the right operand, dict2.

Adding to a Dictionary Using the Update |= Operator:

The dictionary update can be performed using the |= operator, represented by the combination of the pipe (|) and equal sign (=) characters. This operator allows you to modify a dictionary by incorporating the contents of another dictionary or specific values.
Similar to the behavior of the merge (|) operator, when employing the update |= operator, the value associated with a particular key is taken from the right operand if that key exists in both dictionaries.
Here is an example showing the process of creating two dictionaries, utilizing the update operator to add the contents of the second dictionary to the first one. Subsequently displaying the modified dictionary:

Example:


site = {'Website':'example.com', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sandy'}
guests = {'Guest1':'Sammy', 'Guest2':'Xray'}
site |= guests
print("site: ", site)
In this instance, the first_dict initially contains values for keys ‘a’ and ‘b’, while the second_dict includes values for keys ‘b’ and ‘c’. After applying the update operation, the ‘b’ key’s value from the second_dict is incorporated into the first_dict, resulting in the output showing the merged dictionary with updated values.

Save $100 in the next
5:00 minutes?

Register Here
Output:

site:  {'Website': 'example.com', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sandy', 'Guest1': 'Sammy', 'Guest2': 'Xray'}

In the previous example, generating a third dictionary object was not required since the update operator directly modifies the original object. The output of the example indicates that the contents of the “guests” dictionary were added to the original “site” dictionary.

Conclusion:

In this article, various techniques were used to both append data to and update Python dictionaries.