A Beginner’s Guide to Python Dictionaries

Download Now: Free Introduction to Python
Athena Ozanich
Athena Ozanich


Welcome to an awesome Python post about the dictionary data collection type. Data collection types are Python data structures for working with collections of data for various purposes. Python dictionaries are used for a variety of functions, from storing user information to storing collections of users.

python dictionary illustration

In this post, we will discuss what the dictionary data type is and how it works. We will also look at a few examples of what a Python dictionary looks like and ways we can use them.

Without further ado, let's slide on in.

Download Now: An Introduction to Python [Free Guide]

What is a dictionary in Python?

A Python dictionary is a collection of key-value pairs. It is an unordered and changeable data type in Python that works like an associative array or hash table. A dictionary can store any number of elements, and each element can be accessed by its associated key. Dictionaries can support post-creation changes, but dictionaries are strict about duplicate entries. All key/value pairs must be unique.

Once you've created a dictionary, you can access the items using the key for each value.

How to Create a Dictionary in Python

Creating a dictionary in Python is simple enough. You start by declaring a variable, then by using the assignment operator — = — we will assign data to it. The deciding factor on what makes it a dictionary is the use of curly braces — {} — to wrap the data we are assigning. Let's look at how to do this and break it into manageable pieces.

We'll assume we are working with the following dictionary object for the remainder of this post.

snekDict = { "Cobra": "Elapids", "Ball": "Python", "Trimeresurus": "Viper"}

In the dictionary above, we have a collection of snake names and their corresponding types. Printing this to the console is done with the following line.


Accessing Python Dictionary Items

There are several ways you can access the items within a Python dictionary. Python provides built-in methods for interacting with dictionaries. However, the standard way to access items is using the bracket notation, which we will look at next.

Python Dictionary Bracket Notation

To access a single item in the dictionary, you can use the bracket notation to target an item with the keys. For example, to get the snake type for a Cobra, you use the following syntax to target the item you want.


This line of code would print to the console the following response:


Python Dictionary get() Method

The bracket notation is not the only way to get information for a dictionary; Python also offers the get() method. The get method — much like the bracket notation — gets a value based on the key you provide. Let's see what that looks like next.

x = snekDict.get("Cobra")

Python Dictionary keys() Method

The keys method accesses all keys within the dictionary. This lets us check for all available keys.

x = snekDict.keys() print(x)

Running this line of code against our dictionary would return a list of all current keys within the dictionary. To print this to the console would give us the following response.

dict_keys(['Cobra', 'Ball', 'Trimeresurus'])

Python Dictionary values() Method

The values method is similar to the keys method, except it returns all of the values within the dictionary. The values() method is useful for many reasons, such as if a value needs to be changed, the values method can identify what values are in the dictionary and where they are.

x = snekDict.values() print(x)

After printing the results to the console, you would see the following:

dict_items( ['Elapid', 'Python', 'Viper'] )

Python Dictionary items() Method

The Python items method returns the full length of the dictionary, including both the keys and values within it. This method is beneficial because when we need to alter the dictionary, which is often done with automation. Automation is a very common use for Python, and methods like this allow users to modify the dictionary based on set conditions.

x = snekDict.items() print(x)

Much like the keys and values methods, this will return a full list of the dictionary, with both keys and values included.

dict_items( [ ('Cobra', 'Elapid'), ('Ball', 'Python'), ('Trimeresurus', 'Viper') ] )

How to Add to a Python Dictionary

Items in a dictionary can be altered after creation, adding new entries to the dictionary. This ability to add to the dictionary makes it a great choice for long-term data collections that are expected to grow.

The bracket notation can add a new item, target a new key, and assign a new value. Let's start with looking at how you can add to the Python dictionary with the bracket notation.

snekDict[ "Rattlesnake" ] = "Viper"

This code adds a new item to the dictionary, with a key of "Habitat" and a value of "Tropical."

The other way to add new items also updates existing items. The update method will update an existing item, and if it does not exist, it will add it to the dictionary. Next, let's look at how to remove items from the dictionary, then we will discuss some of the common methods used with the Python dictionary object.


snekDict.update({"Rattlesnake": "Pit Viper"})

This line updates the existing item with the key of "Habitat," thus changing its value from "Desert" to "Tropical," fixing the incorrect information.

How to Remove Items From a Python Dictionary

Removing an item from a Python dictionary can be important for several reasons. For example, in the case of our snekDict, we might need to remove a snake from our dictionary if it becomes inapplicable to our needs.

Let's remove an item from our list to see how this works using the various techniques available.

Remove Item Using the pop() Method

The pop method removes an item from the dictionary based on the target key, allowing us to reshape the dictionary as needed.


This method will remove the dictionary item and return the value of the key targeted.

Remove Item Using the popitem() Method

The popitem method removes the last item in the dictionary. As such, its use cases are a bit limited.


Remove Item Using the del Keyword

This keyword is used in front of a dictionary call to the target item using the bracket notation to specify the key. This process may sound confusing, but it's easy; let's look at an example of how you would use the del keyword.

del snekDict["RattleSnake"]

The del keyword can also be used to delete entire dictionaries which is useful for many data needs, such as deleting user data for a login session.

del snekDict

Remove Item Using the clear() Method

The clear method empties the contents of a dictionary while leaving the dictionary object intact.


Other Python Dictionary Methods

We haven't discussed three other Python dictionary methods yet, and each serves its unique benefits. So, let's look at all three and how they can fulfill your development needs.

Python Dictionary copy() Method

The copy method creates a copy of the original target dictionary. This method is beneficial for storing data temporarily before moving to update action. It is also useful for observing or manipulating data while still preserving the original information, the basics behind saving backup data. Let's build on this understanding and other purposes it can be used for by looking at how this works.

tempSnekDict = snekDict.copy()

Not much to look at here; it simply creates a copy and assigns it to the variable.

Python Dictionary fromKeys() Method

The fromKeys() method returns a dictionary based on the provided keys, and it comes with an optional parameter that sets the value of each dictionary item. This can be very useful for initializing a new dictionary with temporary information, such as initial values or messages to add or update information. If you don't supply the second parameter, the returned object is a new dictionary with unassigned values.

snekTraitsDict = dict.fromkeys(('Features', 'Colors', 'Size'), "default")

This would create a dictionary named snekTraitsDict which would contain three keys, all with the same default value. You can even create a list of values and add it as a single value for the keys.

snekTraitsDict = dict.fromkeys(('Features', 'Colors', 'Size') , ("null", "red", 0))

Each of the keys would be given the value provided as the second parameter, printing the result would show the following response.

{ 'Features': ('null', 'red', 0), 'Colors': ('null', 'red', 0), 'Size': ('null', 'red', 0) }

Python Dictionary setDefault() Method

The setDefault method accepts two parameters, the first is a key, and the second is a default value if the key is not present. The first parameter is used to return a dictionary key's value. If the key does not exist within the dictionary, it adds a default value from the second parameter.

Using setDefault on our snekDict dictionary object, we can check if a snake is already in the collection, and if not, add it and assign a default value to the item.

x = snekDict.setdefault("Rattlesnake", "Viper")

In this example, we know we added the Rattlesnake to our dictionary earlier. As a result, this would ignore the value provided and return the value of our Rattlesnake item. If that key did not exist already, it would add the key with a default value of Viper.

Using Python Dictionaries to Improve Your Organization

There are a lot of uses that come with Python dictionaries, and there are many ways to interact with dictionaries. Dictionaries are only improved by nested dictionaries, which may be many layers deep if needed.

Always practice what you learn to help solidify the information. With that in mind, this post is a perfect guide to exploring Python dictionaries from start to finish. Then, try using them to create your data structures, which can help you build a prototype architecture for your database needs.



Topics: What Is Python?

Related Articles

A guide for marketers, developers, and data analysts.

    CMS Hub is flexible for marketers, powerful for developers, and gives customers a personalized, secure experience