Hi, my name is Mary and I am a senior instructor at Juni Learning. Welcome to this basic dictionary Python tutorial!
Today we will talk about how to create a dictionary and append data to it in Python. Specifically, we will learn how to create an empty dictionary and append key-value pairs to it, as well as how to create a dictionary that is initialized with key-value pairs already in it. Additionally, we will go over how to access values using dictionary keys and how to check if a certain key is contained in a dictionary.
By the end of this tutorial you will be able to create your own dictionaries and interact with them!
Who is this for?
Juni Level: Python Level 2 Coding Language: Python Coding Experience: Intermediate Challenge Level: Medium Approx lines of code: ~5
Learning outcomes
Core Concepts Practiced Dictionaries Creating data structures
Prerequisite concepts to know/review:
Conditionals
Demo
Keep in mind: Python dictionaries are another data type that allow us to store two pieces of data together in a key-value pair. You can think of Python dictionaries just like physical dictionaries you may have seen in school or the library! Physical dictionaries store words and their associated definitions. In this case, the key is the word you are defining and the value is the definition of that word. Python dictionaries can work with words and their definitions, but we can also store other things! In this tutorial we will be storing items on our grocery list and their prices. The item will be the key and the price will be the value.
Steps to create a dictionary with Python
- Create an empty dictionary
- Append items to your dictionary
- Print your dictionary
- Create a dictionary with items already in it
- Access a value in a dictionary using a key
- Check if a key exists within a dictionary
Step 1: Create an empty dictionary
First we will create an empty dictionary. We will do this by creating a variable name for our dictionary, in this case dictionary, and setting it equal to a set of curly braces, {}. This will initialize an empty dictionary for us to fill in.
An alternative way to initialize an empty dictionary is to set the variable equal to dict()!
Step 2: Append items to your dictionary
Next we are going to append some dictionary elements. As a reminder, dictionaries store data in the format key-value, so when appending we have to remember both of those parts. As a result, appending to dictionaries looks pretty different from how we append to other data structures like lists, arrays or sets! Here is the syntax on how to do so:
To break this down, we write the name of our dictionary, then our new key in a set of square brackets, [], and we set this equal to the value. As mentioned previously, we are storing items on our grocery list and their prices!
Step 3: Print your dictionary
Now let’s print our existing dictionary to see how it appears in the console:
Notice the format - first we have a key followed by a colon followed by a value. All of our key-value pairs are separated by a comma.
Step 4: Create a dictionary with items already in it
If you know from the start of your code what items you want in your dictionary, you could also initialize your new dictionary with existing keys and values preloaded into it. This approach is great as it takes less lines of code than initializing an empty dictionary and appending each individual key-value pair. Here is the syntax on how to create and an entire dictionary act once:
Dictionaries initialized like this are still mutable, which means we can still append more values to them like we went over in step 2!
Step 5: Access a value in a dictionary using a key
What if you want to look up a value in your dictionary? For example, say you forgot the price of milk and you want to look it up. Here is the syntax on how to do so:
Here we are indexing into our dictionary using our dictionary key to find its corresponding value! This makes sense going back to our physical dictionary comparison - we are able to find the definitions of words by alphabetically looking up the word we want to define. This is a little harder to do for a Python dictionary than in a physical dictionary though as the Python dictionary keys are unordered.
Step 6: Check if a key exists within a dictionary
Finally, our last step is to check if a key exists within our dictionary. We can do this using conditional statements. Lets first check if “tomato” is a dictionary value then if "egg" is a dictionary value. We will add corresponding print statements depending on which conditional is true.
In this step, we are iterating through a dictionary behind the scenes to see if the dictionary key is anywhere in the dictionary. As you can see, the syntax for a conditional that checks if a key is in a dictionary looks like:
if key name in dictionary name:
Want more of a challenge? Try adding these bonus features.
Extra features:
What if we want to combine dictionaries - for example, say we wanted to combine “prices” and “dictionary” into one dictionary to more easily look up the price of any item we might want from the grocery store. There are a few ways we can do this, but the one I am going to go over today involves using the update function. The format looks like:
First dictionary.update(second dictionary)
As a result, if you print the first dictionary, it will have been updated to also contain the values of the second dictionary!
Creative Suggestions
Try playing around with mismatching data types in your dictionary! There is no rule on what data type has to be the key or value, so get creative! Some suggestions for dictionaries include your favorite sports players and their corresponding number or team, numbers and their perfect squares, or anything else you can think of. So try making your own dictionary, it can have as many key-value pairs as you want. Try to figure out how to store a nested dictionary as a value- as a hint, it looks similar to how I stored a list as a value, Another suggestion to try on your own is to add key-value pairs to a dictionary using a for loop!
Great job — now check out more tutorials!
Thanks for reading and I hope you had fun making this project with me!
Built the project above? We'd love to see it! If you're interested in sharing your coding project or experiences with diversity in STEM, please reach out to us at hello@learnwithjuni.com.
Every week, we’ll be posting project tutorials like this one, for different coding languages and experience levels, as well as math tutorials.
Visit our coding projects blog page to find our other tutorials in more coding languages! You can also subscribe to our newsletter using the form to the right of this page for more updates on our programs and newest coding tutorials.
Need more help, or want to keep learning?
Looking up your coding questions is one of the best ways to learn!
Another great way to learn is from an experienced coder or instructor.
Juni Learning coding instructors work closely with students ages 8-18, and are specially trained to adapt to each child's unique learning style, pace, and interests.
Read more about our coding courses and curriculum, or speak with a Juni Advisor by calling (650) 263-4306 or emailing advisors@learnwithjuni.com to learn more about our coding curriculum and our approach to online learning.