

Adding to a Dict in Python – How to Add to a Dictionary
source link: https://www.freecodecamp.org/news/adding-to-a-dict-in-python-how-to-add-to-a-dictionary/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

December 22, 2022 / #Python
Adding to a Dict in Python – How to Add to a Dictionary

A Python dictionary is like a JavaScript object – it’s a sequence of key:value
pairs. So, you can create them like this:
stack_dict = {
"frontend": "JavaScript",
"backend": "Node JS",
"markup": "HTML and JSX",
}
To access the value in the dictionary, you can do it this way: dict[key]
. For example, if I want to access what the frontend
key holds, I can do it like this:
print(stack_dict["frontend"])
# JavaScript
But what if you want to add another entry to the dictionary without going back to the dictionary to put it there? That's what we are going to look at in this article. And I'm going to show you how to do it in 3 different ways.
What We'll Cover
How to Add to a Dictionary in Python
You can add to a dictionary in three different ways:
- map a key to the dictionary
- use the
update()
method - use an if statement
How to Add to a Dictionary in Python by Mapping a key to the Dictionary
If you want to add to a dictionary with this method, you'll need to add the value with the assignment operator.
dict["key"] = "value"`
This would also override the value of an existing key.
In the stack dictionary I defined earlier, there's no styling there:
stack_dict = {
"frontend": "JavaScript",
"backend": "Node JS",
"markup": "HTML and JSX",
}
So let's add a styling
key and CSS
value to the dictionary by mapping a new key to the dictionary:
stack_dict["styling"] = "CSS"
print(stack_dict)
# Output: {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS'}
You can see that a new key of styling
and a value of CSS
has been added to the dictionary.
If the key already exists, the value gets overwritten:
stack_dict["markup"] = "HTML only"
print(stack_dict)
# {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML only'}
How to Add to a Dictionary in Python Using the update()
Method
The stack is still missing a JavaScript library, so let's add it with the update()
method. You can do that this way:
dict.update({"key": "value"})`.
So, to add the JavaScript framework/library, I did it like this:
stack_dict.update({"JS Framework": "React/Next"})
print(stack_dict)
# {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS', 'JS Framework': 'React/Next'}
The update()
also overwrites an existing value if it's different:
stack_dict.update({"backend": "Django"})
print(stack_dict)
# {'frontend': 'JavaScript', 'backend': 'Django', 'markup': 'HTML and JSX'}
How to Add to a Dictionary in Python Using the if
Statement
If you don't want an entry to be overwritten even if it already exists, you can use an if
statement. You can do it with this syntax:
if "value" not it dict.keys():
dict["key"] = "value"
I want to add a "CSS Framework" key with a value of "Tailwind CSS" to the stack dictionary, so I'm going to do that with the help of this syntax:
if "Tailwind CSS" not in stack_dict.keys():
stack_dict["CSS Framework"] = "Tailwind CSS"
print(stack_dict)
# {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS', 'JS Framework': 'React/Next', 'CSS Framework': 'Tailwind CSS'}
If the entry is already in the dictionary, it won't be added in there:
if "HTML and JSX" not in stack_dict.keys():
stack_dict["markup"] = "HTML and JSX"
print(stack_dict)
# {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS', 'JS Framework': 'React/Next'}
If you don't feel like using an if
statement to add to the dictionary, you can do the same thing with try…except…
:
try:
stack_dict["Deployment"] = "Anywhere possible"
except:
print("An exception occurred")
print(stack_dict)
# {'frontend': 'JavaScript', 'backend': 'Node JS', 'markup': 'HTML and JSX', 'styling': 'CSS', 'JS Framework': 'React/Next', 'Deployment': 'Anywhere possible'}
Conclusion
This article took you through three different ways to add to a dictionary in Python:
- mapping a key to the dictionary
- using the update() method
- using an if statement
We even looked at how you can add to a dictionary with the try…except…
expression.
Thank you for reading.
Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.
If you read this far, thank the author to show them you care.
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Recommend
-
10
Update key-value pairs – thispointer.comThis 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...
-
7
OrderedDict vs dict in Python: The Right Tool for the Job
-
9
Dict Cc Dictionary – Bank NXTSkip to content Bank NXT If you want to copy vo...
-
7
一个奇怪的Python Dict表达式 从https://dbader.org/blog/python-mystery-dict-expression 中看到了一个很奇怪的dict表达式: {True: 'yes', 1: 'no', 1.0: 'm...
-
13
-
15
Python program to Add key:value pair to dictionarySkip to content
-
5
In Python, a dictionary is a fat structure that is unordered by default. So, sometimes, you'll want to sort dictionaries by key or value to make queries easier. The problem is that sorting a dictionary by value is never a straightforward th...
-
5
January 6, 2023 /
-
7
February 28, 2023 /
-
8
February 22, 2023 /
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK