Python Programming Language: How to Add Elements To a Dictionary

Jesse L
2 min readJun 30, 2022

Hi everyone, welcome back. In these examples, we will be going over how to add elements into a dictionary in Python. Dictionaries can be used to store a collection of data. Dictionaries use key-value pairs to store data compared to using index numbers. Dictionaries are mutable and does not allow for duplicate keys. For Python 3.7 and higher, dictionaries are ordered whereas in earlier versions, dictionaries are unordered. With this introduction out of the way, let’s get into it.

Creating Dictionary

Let’s start by creating our dictionary:

myDictionary = {
"first": "A",
"second": "B",
"third": "C",
}
print(myDictionary)
Output:
{'first': 'A', 'second': 'B', 'third': 'C'}

So now, we have a populated dictionary with a few elements. We can verify that it was successfully created and populated by printing the dictionary and checking the output. Now let’s see how we can add new elements.

Adding Elements Into The Dictionary

Let’s try to add an element into our dictionary. We can do this by creating a new key and assigning a value to it. Let’s see an example:

myDictionary = {
"first": "A",
"second": "B",
"third": "C",
}
myDictionary["fourth"] = "D"
print(myDictionary)
Output:
{'first': 'A', 'second': 'B', 'third': 'C', 'fourth': 'D'}

In the example above, we can see that we added a new element into our dictionary by creating a new key and assigning a new value. We can verify that it was successfully added by printing the dictionary and checking the output.

We can also add a new element into the dictionary by using the built in update() function that is provided. Let’s see an example:

myDictionary = {
"first": "A",
"second": "B",
"third": "C",
}
myDictionary.update({"fourth": "D"})
print(myDictionary)
Output:
{'first': 'A', 'second': 'B', 'third': 'C', 'fourth': 'D'}

In the example above, we can see that we have added a new element into our dictionary by using the update() function. We can verify that an element was added by printing our set and checking the output. The update() function will add a new element if the given key doesn’t exist, otherwise it will modify the value corresponding to the key.

Conclusion

That is it for adding elements into a dictionary in Python. We covered how to add elements by creating a key directly. We also went over the update() function. I hope this helps. If you have any questions or comments, please let me know. Thanks for reading.

Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.