Python Programming Language: How to Add Elements To a Dictionary
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"…