Python Dictionaries Explained – Complete Guide with Real Examples

Python Dictionaries are one of the most powerful and commonly used data structures in Python. They allow you to store data as key-value pairs, making it easy to organize, access, and manage information efficiently.

Whether you're building web applications, working with APIs, handling JSON data, or developing AI and machine learning projects, dictionaries are used everywhere. In this complete guide, you'll learn everything about Python Dictionaries with easy explanations, practical examples, interview questions, and best practices.


Table of Contents

  • What is a Dictionary in Python?
  • Features of Dictionaries
  • How to Create a Dictionary
  • Access Dictionary Values
  • Add New Items
  • Update Existing Values
  • Remove Items
  • Dictionary Methods
  • Loop Through Dictionaries
  • Nested Dictionaries
  • Real-World Examples
  • Common Mistakes
  • Interview Questions
  • FAQs
  • Summary

What is a Dictionary in Python?

A Dictionary is a built-in Python data structure that stores data in the form of key-value pairs. Each key in a dictionary is unique, and every key is associated with a value.

Unlike lists, dictionaries do not use numeric indexes. Instead, values are accessed using their corresponding keys.

Syntax


student = {
    "name": "Ankur",
    "age": 24,
    "course": "Python"
}

Output


{
 'name': 'Ankur',
 'age': 24,
 'course': 'Python'
}

Why Use Dictionaries?

  • Store data as key-value pairs.
  • Fast data lookup using keys.
  • Easy to update and modify data.
  • Perfect for JSON and API responses.
  • Widely used in Django, Flask, FastAPI, and AI projects.

Features of Python Dictionaries

Feature Description
Mutable Dictionary values can be changed after creation.
Ordered Python 3.7+ preserves insertion order.
Unique Keys Duplicate keys are not allowed.
Key-Value Structure Stores information in key-value format.
Fast Lookup Accessing values using keys is very efficient.

Creating a Dictionary

Example 1


person = {
    "name": "John",
    "age": 30,
    "city": "Delhi"
}

print(person)

Output


{'name': 'John', 'age': 30, 'city': 'Delhi'}

Example 2: Empty Dictionary


employee = {}

print(employee)

Output


{}

Accessing Dictionary Values

You can access values using their keys.


student = {
    "name": "Ankur",
    "age": 24,
    "course": "Python"
}

print(student["name"])
print(student["course"])

Output


Ankur
Python

Using get() Method

The get() method returns the value for a key without raising an error if the key does not exist.


student = {
    "name": "Ankur",
    "age": 24
}

print(student.get("name"))
print(student.get("city"))

Output


Ankur
None

Adding New Items


student = {
    "name": "Ankur",
    "age": 24
}

student["city"] = "Delhi"

print(student)

Output


{
 'name': 'Ankur',
 'age': 24,
 'city': 'Delhi'
}

Updating Existing Values


student = {
    "name": "Ankur",
    "age": 24
}

student["age"] = 25

print(student)

Output


{
 'name': 'Ankur',
 'age': 25
}


Removing Items from a Dictionary

Python provides multiple ways to remove items from a dictionary depending on your requirement.

Using pop()

The pop() method removes the specified key and returns its value.


student = {
    "name": "Ankur",
    "age": 24,
    "city": "Delhi"
}

student.pop("city")

print(student)

Output


{
 'name': 'Ankur',
 'age': 24
}

Using del Keyword


student = {
    "name": "Ankur",
    "age": 24,
    "city": "Delhi"
}

del student["age"]

print(student)

Output


{
 'name': 'Ankur',
 'city': 'Delhi'
}

Using clear()

The clear() method removes all items from the dictionary.


student = {
    "name": "Ankur",
    "age": 24
}

student.clear()

print(student)

Output


{}

Important Dictionary Methods

Method Description
get() Returns the value of a key safely.
keys() Returns all dictionary keys.
values() Returns all values.
items() Returns key-value pairs.
update() Updates dictionary values.
pop() Removes a key.
clear() Removes all items.
copy() Creates a copy of the dictionary.

Using keys()


student = {
    "name": "Ankur",
    "age": 24,
    "city": "Delhi"
}

print(student.keys())

Output


dict_keys(['name', 'age', 'city'])

Using values()


student = {
    "name": "Ankur",
    "age": 24,
    "city": "Delhi"
}

print(student.values())

Output


dict_values(['Ankur', 24, 'Delhi'])

Using items()


student = {
    "name": "Ankur",
    "age": 24,
    "city": "Delhi"
}

print(student.items())

Output


dict_items([('name', 'Ankur'), ('age', 24), ('city', 'Delhi')])

Using update()


student = {
    "name": "Ankur",
    "age": 24
}

student.update({
    "city": "Delhi",
    "course": "Python"
})

print(student)

Output


{
 'name': 'Ankur',
 'age': 24,
 'city': 'Delhi',
 'course': 'Python'
}

Loop Through a Dictionary

You can loop through a dictionary using a for loop.

Loop Through Keys


student = {
    "name": "Ankur",
    "age": 24,
    "city": "Delhi"
}

for key in student:
    print(key)

Loop Through Values


for value in student.values():
    print(value)

Loop Through Keys and Values


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

Nested Dictionaries

A dictionary can also contain another dictionary, which is called a Nested Dictionary.


students = {
    "student1": {
        "name": "Ankur",
        "age": 24
    },
    "student2": {
        "name": "Rahul",
        "age": 22
    }
}

print(students)

Real-World Example

Dictionaries are commonly used to store user profiles, API responses, configuration settings, and product information.


user = {
    "id": 101,
    "name": "Ankur",
    "email": "ankur@example.com",
    "isPremium": True
}

print(user["email"])

Output


ankur@example.com

Common Mistakes

  • Using duplicate keys (the last value overwrites the previous one).
  • Accessing a missing key using square brackets instead of get().
  • Trying to use mutable objects like lists as dictionary keys.
  • Modifying a dictionary while iterating over it.

Best Practices

  • Use meaningful key names.
  • Prefer get() when a key may not exist.
  • Use items() when both keys and values are needed.
  • Keep dictionaries organized and avoid deeply nested structures unless necessary.


Dictionary Comprehension

Dictionary Comprehension is a concise and efficient way to create dictionaries in Python. It works similarly to list comprehensions but produces a dictionary instead of a list.

Syntax


{key: value for item in iterable}

Example


numbers = [1, 2, 3, 4, 5]

square = {num: num ** 2 for num in numbers}

print(square)

Output


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

Dictionary vs List

Dictionary List
Stores data as Key : Value pairs Stores ordered values
Access using Keys Access using Index
Keys must be unique Duplicate values allowed
Faster lookup Sequential lookup

Real-World Use Cases

1. Student Information


student = {
    "name": "Ankur",
    "age": 24,
    "course": "Python",
    "marks": 92
}

2. Product Details


product = {
    "id": 101,
    "name": "Laptop",
    "price": 65000,
    "stock": 20
}

3. API Response


response = {
    "status": 200,
    "message": "Success",
    "data": {
        "username": "ankur"
    }
}

4. Employee Record


employee = {
    "id": 501,
    "name": "Rahul",
    "department": "IT",
    "salary": 50000
}

Interview Questions

1. What is a Dictionary in Python?

A Dictionary is a mutable data structure that stores data as key-value pairs.


2. Can Dictionary Keys be Duplicate?

No. Dictionary keys must always be unique. If duplicate keys are provided, the last value replaces the previous one.


3. Can Dictionary Values be Duplicate?

Yes. Multiple keys can have the same value.


4. What is the Difference Between get() and [] ?

The get() method returns None if a key does not exist, whereas square brackets raise a KeyError.


5. Is Dictionary Ordered?

Yes. From Python 3.7 onwards, dictionaries preserve insertion order.


Practice Questions

  1. Create a dictionary containing student information.
  2. Add a new key named email.
  3. Update the student's age.
  4. Delete the course key.
  5. Print all keys using the keys() method.
  6. Print all values using the values() method.
  7. Loop through the dictionary.
  8. Create a nested dictionary.
  9. Create a dictionary using Dictionary Comprehension.
  10. Build a product catalog using dictionaries.

Frequently Asked Questions (FAQs)

Why should I use a Dictionary?

Dictionaries provide fast data lookup and are ideal for storing structured information such as user profiles, products, settings, and JSON data.


Can a Dictionary contain another Dictionary?

Yes. This is called a Nested Dictionary.


Can I store a List inside a Dictionary?

Yes. Dictionaries can store lists, tuples, sets, and even other dictionaries as values.


Which method is safest for accessing values?

The get() method is considered safer because it avoids KeyError.


Summary

Python Dictionaries are one of the most important data structures every Python developer should master. They allow you to store and manage data efficiently using key-value pairs.

In this guide, you learned:

  • What a Dictionary is
  • How to Create Dictionaries
  • Access, Update and Delete Values
  • Dictionary Methods
  • Looping Through Dictionaries
  • Nested Dictionaries
  • Dictionary Comprehension
  • Real-world Examples
  • Interview Questions
  • Best Practices

Related Python Articles


Conclusion

Understanding Python Dictionaries is essential for every Python developer. From beginner projects to advanced applications like web development, APIs, automation, and artificial intelligence, dictionaries are used everywhere.

Practice the examples shared in this guide and experiment with different dictionary methods to strengthen your Python programming skills.


💡 If you found this article helpful, share it with your friends and bookmark it for future reference.

Happy Coding! 🐍🚀

Comments

Popular posts from this blog

How to Fix npx tailwindcss init Error: “Could Not Determine Executable to Run”

🛠️ How to Create a React App with Vite and Tailwind (Beginner Guide)

✅ Logical Operators in JavaScript – Complete Guide with Real Examples