- How To Add to a Dictionary in Python
- Adding to a Dictionary Using the = Assignment Operator
- Adding to a Dictionary Without Overwriting Values
- Adding to a Dictionary Using the update() Method
- Adding to a Dictionary Using the Merge | Operator
- Adding to a Dictionary Using the Update |= Operator
- Conclusion
- Adding to Dict in Python – How to Append to a Dictionary
- How to add a single key-value pair to a dictionary
- How to add multiple key-value pairs with the update() method
- How to update a dictionary using the dict() constructor
- Conclusion
- Python Add to Dictionary – Adding an Item to a Dict
- How to Create a Dictionary in Python
- Features of a Dictionary
- Duplicate Keys Are Not Allowed
- Items in a Dictionary Are Changeable
- Items in a Dictionary Are Ordered
- How to Add an Item to a Dictionary
- Conclusion
How To Add to a Dictionary in Python
Dictionary is a built-in Python data type. A dictionary is a sequence of key-value pairs. Dictionaries are mutable objects, however, dictionary keys are immutable and need to be unique within each dictionary. There’s no built-in add method, but there are several ways to add to and update a dictionary. In this article, you’ll use the Python assignment operator, the update() method, and the merge and update dictionary operators to add to and update Python dictionaries.
Adding to a Dictionary Using the = Assignment Operator
You can use the = assignment operator to add a new key to a dictionary:
If a key already exists in the dictionary, then the assignment operator updates, or overwrites, the value.
The following example demonstrates how to create a new dictionary and then use the assignment operator = to update a value and add key-value pairs:
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)
Outputoriginal dictionary: updated dictionary:
The output shows that the value of a is overwritten by the new value, the value of b is unchanged, and new key-value pairs are added for c and d .
Adding to a Dictionary Without Overwriting Values
Using the = assignment operator overwrites the values of existing keys with the new values. If you know that your program might have duplicate keys, but you don’t want to overwrite the original values, then you can conditionally 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)
Outputoriginal dictionary: updated dictionary: conditionally updated dictionary:
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 append a dictionary or an iterable of key-value pairs to a dictionary using the update() method. The update() method overwrites the values of existing keys with the new values.
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':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary'> print("original dictionary: ", site) # update the dictionary with the author key-value pair site.update('Author':'Sammy Shark'>) print("updated with Author: ", site) # create a new dictionary guests = 'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'> # update the original dictionary with the new dictionary site.update(guests) print("updated with new dictionary: ", site)
Outputoriginal dictionary: updated with Author: updated with new dictionary:
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, then the old value is overwritten by the update.
Adding to a Dictionary Using the Merge | Operator
You can use the dictionary merge | operator, represented by the pipe character, to merge two dictionaries and return a new dictionary object.
The following example demonstrates how to to create two dictionaries and use the merge operator to create a new dictionary that contains the key-value pairs from both:
site = 'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sammy'> guests = 'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'> new_site = site | guests print("site: ", site) print("guests: ", guests) print("new_site: ", new_site)
Outputsite: guests: new_site:
The two dictionaries were merged into a new dictionary object that contains the key-value pairs from both dictionaries.
If a key exists in both dictionaries, then 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>
The value of key b was overwritten by the value from the right operand, dict2 .
Adding to a Dictionary Using the Update |= Operator
You can use the dictionary update |= operator, represented by the pipe and equal sign characters, to update a dictionary in-place with the given dictionary or values.
Just like the merge | operator, if a key exists in both dictionaries, then the update |= operator takes the value from the right operand.
The following example demonstrates how to create two dictionaries, use the update operator to append the second dictionary to the first dictionary, and then print the updated dictionary:
site = 'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sammy'> guests = 'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'> site |= guests print("site: ", site)
In the preceding example, you didn’t need to create a third dictionary object, because the update operator modifies the original object. The output shows that the guests dictionary was appended to the original site dictionary.
Conclusion
In this article, you used different methods to add to and update a Python dictionary. Continue your learning with more Python tutorials.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Adding to Dict in Python – How to Append to a Dictionary
Shittu Olumide
A dictionary in Python is a group of unordered items, each of which has a unique set of keys and values.
Any immutable data type, such as a string, number, or tuple, can be used as the key. It serves as an exclusive identifier for the value in the dictionary. The value is repeatable and applicable to all types of data.
In Python, dictionaries are denoted by curly braces < >, and each key-value pair is delimited by a colon : . A comma separates the key and value. Here is an illustration of a basic dictionary:
In this example, «pineapple», «apple», «orange», and «avocado» are the keys, and 12, 30, 5 and 7 are the corresponding values.
We will have a look at how we can add a single key-value pair to a dictionary using the update() method, and finally the dict() constructor.
How to add a single key-value pair to a dictionary
To add a single key-value pair to a dictionary in Python, we can use the following code:
The above code will create a dictionary myDict with two key-value pairs. Then we added a new key-value pair ‘c’ : 3 to the dictionary by just assigning the value 3 to the key ‘c’ . After the code is executed, the dictionary myDict will now contain the key-value pair ‘c’: 3 .
Let’s confirm this by printing the dictionary.
If there is a key ‘c’ in the dictionary already, the value would be updated to 3.
How to add multiple key-value pairs with the update() method
Multiple key-value pairs can be simultaneously added to a dictionary using the update() method. This method inserts new entries into the original dictionary from another dictionary or an iterable of key-value pairs as input. The value of an existing key in the original dictionary will be updated with the new value.
Example using the update() method to add multiple entries to a dictionary:
myDict = new_data = myDict.update(new_data) print(myDict)
Another fun thing about this method is that, we can use the update() method with an iterable of key-value pairs, such as a list of tuples. Let’s see this in action.
myDict = new_data = [('c', 3), ('d', 4)] myDict.update(new_data) print(myDict)
The output is the same as the previous example:
How to update a dictionary using the dict() constructor
In Python, a dictionary can be updated or made from scratch using the dict() constructor. By passing a dictionary containing the new key-value pair as an argument to the dict() constructor, we can add a single key-value pair to an existing dictionary.
myDict = newDict = dict(myDict, d=4) print(newDict)
In this example, three key-value pairs were added to a brand-new dictionary called myDict . Then, we created a new dictionary called newDict using the dict() constructor, which also added the key-value pair ‘d’: 4′ .
When the two dictionaries are combined by the dict() constructor, any keys that are present in both dictionaries have their values overwritten by the value from the second dictionary (in this case, ‘d’: 4′ ).
Keep in mind that a new dictionary can also be created using the dict() constructor from a list of key-value pairs, where each pair is represented by a tuple.
MyList = [('a', 1), ('b', 2), ('c', 3)] MyDict = dict(MyList) print(MyDict)
Conclusion
In Python, dictionaries are frequently used to store data and provide quick access to it using a distinct key value. They come in handy when working with lists or tuples, where we need to access data using a specific identifier rather than its place in a sequence.
Let’s connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.
Python Add to Dictionary – Adding an Item to a Dict
Ihechikara Vincent Abba
Data structures help us organize and store collections of data. Python has built-in data structures like Lists, Sets, Tuples and Dictionaries.
Each of these structures have their own syntax and methods for interacting with the data stored.
In this article, we’ll talk about Dictionaries, their features, and how to add items to them.
How to Create a Dictionary in Python
Dictionaries are made up of key and value pairs nested in curly brackets. Here’s an example of a Dictionary:
In the code above, we created a dictionary called devBio with information about a developer – the developer’s age is quite overwhelming.
Each key in the dictionary – name , age and language – has a corresponding value. A comma separates each key and value pair from another. Omitting the comma throws an error your way.
Before we dive into how we can add items to our dictionaries, let’s have a look at some of the features of a dictionary. This will help you easily distinguish them from other data structures in Python.
Features of a Dictionary
Here are some of the features of a dictionary in Python:
Duplicate Keys Are Not Allowed
If we create a dictionary that has two or multiple identical keys in it, the last key out of them will override the rest. Here’s an example:
We created three keys with an identical key name of name . When we printed our dictionary to the console, the last key having a value of «Chikara» overwrote the rest.
Let’s see the next feature.
Items in a Dictionary Are Changeable
After assigning an item to a dictionary, you can change its value to something different.
devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio["age"] = 1 print(devBio) #
In the example above, we reassigned a new value to age . This will override the initial value we assigned when the dictionary was created.
We can also use the update() method to change the value of items in our dictionary. We can achieve the same result in the last example by using the update() method – that is: devBio.update() .
Items in a Dictionary Are Ordered
By being ordered, this means that the items in a dictionary maintain the order in which they were created or added. That order cannot change.
Prior to Python 3.7, dictionaries in Python were unordered.
In the next section, we will see how we can add items to a dictionary.
How to Add an Item to a Dictionary
The syntax for adding items to a dictionary is the same as the syntax we used when updating an item. The only difference here is that the index key will include the name of the new key to be created and its corresponding value.
Here’s what the syntax looks like: devBio[newKey] = newValue .
We can also use the update() method to add new items to a dictionary. Here’s what that would look like: devBio.update(newKey«: newValue>) .
devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio["role"] = "Developer" print(devBio) #
Above, using the index key devBio[«role»] , we created a new key with the value of Developer .
In the next example, we will use the update() method.
devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio.update() print(devBio) #
Above, we achieved the same result as in the last example by passing in the new key and its value into the update() method – that is: devBio.update() .
Conclusion
In this article, we learned what dictionaries are in Python, how to create them, and some of their features. We then saw two ways through which we can add items to our dictionaries.