Dictionaries in Python

Learn Dictionaries in Python with real-life examples. Understand key-value pairs, dictionary methods, loops, dictionary comprehension, and practical use cases in Python programming.

Dictionaries in Python
Dictionaries in Python

When working with Python, sometimes we need to store information in pairs.
For example:

  • A student’s name and their marks
  • A country and its capital
  • A product and its price

For such cases, dictionaries are the best choice in Python!


What is a Dictionary in Python?

A dictionary is a collection of data stored in key-value pairs.

  • The key is like a label (unique).
  • The value is the data linked to that key.

👉 Syntax:

my_dict = {
    "key1": "value1",
    "key2": "value2"
}

Example:

student = {
    "name": "Rahul",
    "age": 20,
    "marks": 85
}
print(student)

Output:

{'name': 'Rahul', 'age': 20, 'marks': 85}

Creating a Dictionary

  1. Empty dictionary
data = {}
  1. With values
car = {"brand": "Toyota", "model": "Fortuner", "year": 2022}
  1. Using dict() constructor
info = dict(name="Amit", age=25, city="Delhi")

Accessing Dictionary Values

You can access values using keys:

student = {"name": "Rahul", "marks": 85}
print(student["name"])   # Rahul
print(student["marks"])  # 85

⚠️ If the key doesn’t exist, it throws an error.
To avoid this, use get():

print(student.get("age", "Not Found"))

Read More: Sets in Python


Updating and Adding Items

student = {"name": "Rahul", "marks": 85}

# Update
student["marks"] = 90

# Add new key-value pair
student["age"] = 20

print(student)

Output:

{'name': 'Rahul', 'marks': 90, 'age': 20}

Removing Items

  1. pop(key) → Removes item with the given key.
student.pop("marks")
  1. popitem() → Removes the last inserted item.
student.popitem()
  1. del → Deletes key or entire dictionary.
del student["name"] # Deletes 'name' key
del student  # Deletes entire dictionary
  1. clear() → Removes all items.
student.clear()

Useful Dictionary Methods

MethodDescriptionExample
keys()Returns all keysstudent.keys()
values()Returns all valuesstudent.values()
items()Returns key-value pairsstudent.items()
update()Updates dictionary with another dictstudent.update({"age": 22})
copy()Returns a shallow copystudent.copy()

Looping Through a Dictionary

student = {"name": "Rahul", "marks": 90, "age": 20}

for key, value in student.items():
    print(key, ":", value)

Output:

name : Rahul
marks : 90
age : 20

Real-Life Examples of Dictionaries

Example 1: Country-Capital Dictionary

capitals = {
    "India": "New Delhi",
    "France": "Paris",
    "Japan": "Tokyo"
}
print("Capital of Japan is:", capitals["Japan"])
# Output: Capital of Japan is: Tokyo

Example 2: Student Marks Record

marks = {
    "Amit": 85,
    "Rahul": 90,
    "Neha": 78
}
print("Rahul's Marks:", marks["Rahul"])
# Output: Rahul's Marks: 90

Example 3: Shopping Cart System

cart = {
    "Laptop": 55000,
    "Mobile": 20000,
    "Headphones": 1500
}

total = sum(cart.values())
print("Total Price:", total)
# Output: Total Price: 76500

Dictionary Comprehension

Just like list comprehension, we can create dictionaries in one line.

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

Output:

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

Final Thoughts

Dictionaries are one of the most powerful data structures in Python.
They are perfect when you want to map information like a real-world dictionary (word → meaning).

In this post, you learned:

  • What dictionaries are
  • How to create, access, update, and delete
  • Useful methods and loops
  • Real-life examples
  • Dictionary comprehension

Mastering dictionaries will make your coding more efficient and help you build real-world projects like student management systems, shopping carts, and APIs.

FAQs – Dictionaries in Python

A list stores data in an ordered sequence (index-based), while a dictionary stores data as key-value pairs (not based on indexes).

No. Keys in a dictionary must be unique. If you add a duplicate key, the latest value will overwrite the previous one.

No. Keys must be immutable types like strings, numbers, or tuples. Lists or other dictionaries cannot be used as keys.

You can use for key, value in dict.items() to loop through both keys and values.

What’s Next?

In the next post, we’ll learn about the Student Management System in Python

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Translate »
Scroll to Top