How To Make A Dictionary In Python

In this tutorial, we will learn how to make a dictionary in Python. A dictionary is a collection of key-value pairs, where each key is associated with a value. Dictionaries are useful for storing and retrieving data by unique keys, instead of using indices for elements like in lists or tuples. In Python, dictionaries are mutable and unordered.

We will go through different methods to create a dictionary, add key-value pairs, and access the stored data.

Step 1: Create an Empty Dictionary

There are two ways to create an empty dictionary in Python: using curly braces ({}) or using the dict function.

This will create an empty dictionary and print it twice. The output will be:

{}
{}

Step 2: Create a Dictionary with Initial Key-Value Pairs

We can also create a dictionary with some initial key-value pairs. Use curly braces ({}) and separate the key-value pairs with commas.

The output will be:

{'apple': 5, 'orange': 10, 'banana': 3}

Step 3: Add Key-Value Pairs to a Dictionary

To add a new key-value pair to the dictionary, provide the new key and assign a value to it using the assignment operator (=).

The output will be:

{'apple': 5, 'orange': 10, 'banana': 3, 'grape': 15}

Step 4: Access Dictionary Values by Key

We can access the value of a key by using square bracket notation or using the get method.

The output will be:

5
10

Step 5: Check If Key Exists in the Dictionary

Before accessing a key-value pair, make sure the key exists in the dictionary using the in operator.

The output will be:

Apple exists in the dictionary

Full Code

Here’s the complete code together:

The output will be:

{}
{}
{'apple': 5, 'orange': 10, 'banana': 3}
{'apple': 5, 'orange': 10, 'banana': 3, 'grape': 15}
5
10
Apple exists in the dictionary

Conclusion

In this tutorial, we learned how to create dictionaries in Python, add key-value pairs to them, access values by keys, and check if a key exists in the dictionary. Knowing how to use dictionaries is essential for working with data collection, as they provide a convenient and efficient way to store and retrieve data by unique keys.