Python Dictionary Tutorial with Codes and Examples in 2023

Article by: Manish Methani

Last Updated: October 5, 2021 at 10:04am IST
5 min 7 sec read

Python dictionaries are an essential data structure used in programming. They are used to store key-value pairs and provide a fast and efficient way to look up data based on a specific key. In this tutorial, we will cover everything you need to know about Python dictionaries, including how to create, modify, and manipulate them, along with codes and examples.

Step 1: Creating a Python Dictionary

To create a Python dictionary, you can use curly braces and specify key-value pairs separated by colons. Here's an example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}

In this example, we created a dictionary with three key-value pairs: 'apple': 1, 'banana': 2, and 'cherry': 3.

Step 2: Accessing Values in a Python Dictionary

To access the values in a Python dictionary, you can use the keys. Here's an example:

print(my_dict['banana'])

In this example, we accessed the value associated with the 'banana' key in the my_dict dictionary, which is 2.

Step 3: Modifying a Python Dictionary

Python dictionaries are mutable, which means that you can add, delete, and modify key-value pairs. Here's an example:

my_dict['apple'] = 5
my_dict['orange'] = 4
del my_dict['cherry']

In this example, we modified the value associated with the 'apple' key to 5, added a new key-value pair 'orange': 4, and deleted the key-value pair associated with the 'cherry' key.

Step 4: Iterating over a Python Dictionary

To iterate over a Python dictionary, you can use a for loop. Here's an example:

for key, value in my_dict.items():
    print(key, value)

In this example, we used the items() method to access both the keys and values in the my_dict dictionary. The output of this code would be:

apple 5
banana 2
orange 4

Example of Dictionary and how to use it

# Dictionary = key : value

# Create a dictionary
d = {"dog" : "bark", "cat" : "meow" }

# Print the type of the variable
print(type(d))

# Print the contents of the dictionary
print(d)

# Get the entry from a dictionary using the key
print(d["cat"])

# KeyError....snakes is not a key in our dictionary 
print(d["snakes"])

# Check if a dictionary has a given key
print("cat" in d)
print("lion" in d)

# Add an element in a dictionary
d["lion"] = "roar"
print(d)

# Delete an element from a dictionary
del d["lion"]
print(d) 

More about Dictionaries

Given a key, get its value from the dictionary. If the key is not in the dictionary, you can specify the default value as well. In this example, the lion is not in the dictionary so the output will be NA. You can assign a default value if the key is not present in dictionary print(d.get('lion', 'Not in the dictionary'))

# Create a dictionary
d = {"dog" : "bark", "cat" : "meow" }
print(d.get("cat"))
print(d.get("lion"))
print(d.get("lion", "Not in the dictionary"))
print(d.get("lion", "NA"))
print(d.get("dog", "NA")) 

What is Dictionary Comprehension?

Dictionary comprehension is a concise way of creating a new dictionary from an iterable object such as a list, tuple, or set. It is similar to list comprehension, but instead of creating a list, it creates a dictionary.

Dictionary comprehension uses curly braces {} to create a dictionary and a colon : to separate the key-value pairs. The syntax of dictionary comprehension is as follows:

{key: value for item in iterable}

How does Dictionary Comprehension work?

The general idea of dictionary comprehension is to iterate over an iterable object and create a new key-value pair for each item in the iterable. The key and value of each pair can be calculated using an expression or function.

Here is an example of a dictionary comprehension that creates a dictionary of squares:

squares = {x: x*x for x in range(1, 6)}
print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

In this example, the iterable object is a range from 1 to 6. The expression x*x calculates the square of each item in the range, and the resulting dictionary has each item in the range as a key and its square as a value.

Explore Codzify Courses

PREMIUM

Learn to create the Dating App using No-Code Tool FlutterFlow

Level: Advanced

Course Fees: INR 1299/-

Apply Coupon Code: UNLOCK

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

Flutter Mobile App Development Course

Level: Intermediate

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

The Complete Angular Course

Level: Beginners

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

Dart Programming for Absolute Beginners

Level: Beginners

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Coming Soon
FREE

Next.js course

Level: Beginners

Course Fees: FREE

Start Watching
FREE

Fundamentals of Computer Programming Languages

Level: Beginners

Course Fees: FREE

Start Watching
FREE

Learn HTML, CSS & Bootstrap

Level: Beginners

Course Fees: FREE

Start Watching

Latest Web Stories

1

Learn how to open WhatsApp using FlutterFlow | Step by Step Guide

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test

Download the Codzify
Mobile App


Learn Anytime, Anywhere at your own pace. Scan the QR Code with your Mobile Camera to Download the Codzify Mobile App.

Codzify Mobile App Codzify Mobile App
Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer