Thursday, November 13, 2025

Understanding Dictionaries in Python – A Beginner-Friendly Guide

 

πŸ” What Is a Dictionary in Python?

A dictionary is a built-in Python data type that stores information in the form of key–value pairs.
It is similar to a real-life dictionary where a word acts as a key and its meaning is the value.

✔ Key Features:

  • Unordered – Items do not have a fixed position.

  • Mutable – You can change, add, or remove items.

  • Key-based access – Values are retrieved using keys, not indexes.

  • No duplicate keys – Each key must be unique


🏷️ Creating a Dictionary

Here’s the simplest example:

student = { "name": "Raghav", "age": 20, "course": "Computer Science" }

This dictionary contains three pieces of information (values) associated with their respective keys.



πŸ“Œ Accessing Dictionary Values

You can get values by using their key:

print(student["name"]) # Output: Raghav print(student["age"]) # Output: 20

If you try to access a non-existent key, Python will raise an error.


πŸ› ️ Adding and Updating Items

Dictionaries are flexible—you can add new key–value pairs or update existing ones anytime.

➕ Add a new item

student["grade"] = "A"

πŸ”„ Update an existing item

student["age"] = 21

πŸ—‘️ Deleting Items From a Dictionary

You can remove items in multiple ways.

Using del

del student["course"]

Using pop()

student.pop("age")

πŸ” Looping Through a Dictionary

Loop through both keys and values using .items():

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

πŸ“š Nested Dictionaries

Dictionaries can contain other dictionaries—useful for organizing complex data.

college = { "student1": {"name": "Raghav", "age": 20}, "student2": {"name": "Aman", "age": 22} } print(college["student1"]["name"]) # Output: Raghav

This structure is widely used in APIs and JSON data.


🧩 Where Are Dictionaries Used?

Python dictionaries are everywhere, especially in:

  • Web development

  • Data analysis

  • Machine learning

  • APIs and JSON

  • Config files

  • Chatbots and NLP

Their power lies in how quickly they retrieve data based on keys.


🏁 Conclusion

Python dictionaries are one of the most useful data structures you will use, thanks to their flexibility and speed. By mastering dictionaries, you can handle real-world data more efficiently and write cleaner, more organized code.

No comments:

Post a Comment

Python Viva Questions

  Basic Python Viva Questions 1. What is Python? Python is a high-level, interpreted, and object-oriented programming language used for w...