This article is part of in the series
Last Updated: Wednesday 29th December 2021

The Python Dictionary (dict): An Overview

Among the built-in Python data types is a very versatile type called a dictionary. The dictionary is similar to lists and tuples because they act as storage units for other objects or variables you’ve created. Dictionaries are different from lists and tuples because the group of objects they hold aren't in any particular order, but rather each object has its own unique name, commonly known as a key.

The objects or values stored in a dictionary can basically be anything (even the nothing type defined as None), but keys can only be immutable type-objects. e.g., strings, tuples, integers, etc.

Note: Immutable types that store objects like tuples can only contain other immutable types to be dictionary keys.

Creating a Python Dictionary

Creating a dictionary is easy, here is an empty one:

Here is one with a few values (note the {key1: value1, key2: value2, ...} structure) :

You can also use the dictionary constructor (note with this method, keys can only be keyword strings):

Get a Python Dictionary's Values

To get one of the values, just use its key:

Remove a Python Dictionary's Key

To remove a key: value pair, simply delete it with the del keyword:

Add a Key to a Python Dictionary

Or to assign a new key, just use the new key:

Overwriting Python Dictionary Key-value Pairs

Note: All the keys in a dictionary are unique, so if you assign a value to an existing key, it will be overwritten! For example:

Swap a Key and Value in a Python Dictionary

If you want to swap or change the key for a value, you can create the new key with the value, then simply delete the old key:

Search a Python Dictionary by Key

To check if a key exists in the dictionary, just use key in smalldict:

Note: This does not check whether a value exists in the dictionary, only a key:

Search a Python Dictionary by Value

To check for a given value, you can use one of the dictionary's standard methods, values.

There are many more useful methods and recipes for dictionary objects, but those are the basics.

Remember, keys don't have to be strings, and can be any immutable object you can create—and values can be just about anything, including other dictionaries. Don't be afraid to be creative and discover what you can do with them!

About The Author