How To Make A Python Dictionary

In this tutorial, we will learn how to create a Python dictionary, which is a mutable, unordered collection of key-value pairs.

Dictionaries are an essential data structure in Python programming, and they are used for a wide range of applications, including storing configuration settings, counting word frequencies, and representing graphs.

This tutorial will guide you through the process of creating and manipulating dictionaries, including adding, updating, and deleting key-value pairs.

Step 1: Create an Empty Dictionary

To create an empty dictionary, you can use the dictionary constructor dict(), or you can use curly brackets {}. Here are two ways to achieve this:

Both of these lines of code create an empty dictionary.

Step 2: Create a Dictionary with Initial Values

To create a dictionary with initial key-value pairs, you can use the following syntax:

In this example, the keys are the strings ‘key1’, ‘key2’, and ‘key3’, and the associated values are the strings ‘value1’, ‘value2’, and ‘value3’. You can replace these example keys and values with your own data.

Step 3: Add or Update Key-Value Pairs

To add a new key-value pair, or update an existing one, you can use the following syntax:

The first line adds a new key-value pair with the key ‘new_key’ and the value ‘new_value’. If ‘new_key’ already exists in the dictionary, its associated value will be replaced with ‘new_value’. The second line updates the value associated with the key ‘key1’ to ‘updated_value1’.

Step 4: Access Values by Key

To access the value associated with a given key, you can use the following syntax:

This line of code will save the value associated with ‘key1’ into the variable ‘value’.

Note that if the specified key does not exist in the dictionary, this will raise a KeyError. To avoid this, you can use the get method, which returns a default value if the key is not found:

In this example, ‘value’ will be assigned to ‘default_value’ if ‘nonexistent_key’ is not found in the dictionary.

Step 5: Remove Key-Value Pairs

To remove a key-value pair from the dictionary, you can use the del keyword followed by the dictionary and the key:

This line of code deletes the key-value pair with the key ‘key1’ from the dictionary.

Step 6: Check If a Key Exists in the Dictionary

To check if a key exists in a dictionary, you can use the in keyword:

The variable ‘key_exists’ will be assigned to True if ‘key1’ is a key in the dictionary, and False otherwise.

Full Code:


Now that you have learned how to create and manipulate Python dictionaries, you can easily use them in a variety of applications. The dictionary data structure provides a powerful and versatile way to store and retrieve data, making it a fundamental component in the Python programming language.