Sunday, 29 June 2025

Python Dictionaries

Python Dictionaries

📘 What is a Dictionary?

A dictionary in Python is a collection of key-value pairs. It's like a real-life dictionary where you look up a word (the key) to find its meaning (the value).

  • 🔑 Keys → The unique identifiers
  • 📦 Values → The data associated with those keys

🔍 Syntax:

my_dict = {
    "name": "Ansh",
    "age": 7,
    "grade": "1st"
}

Here:

  • "name", "age", and "grade" are the keys
  • "Ansh", 7, and "1st" are the values

🧩 Why Use a Dictionary?

  • To store related information (like name, marks, etc.) together
  • To quickly look up data using keys
  • It's organized and flexible

✍️ Creating a Dictionary

Example:

student = {
    "name": "Aarav",
    "age": 14,
    "class": "8th",
    "marks": 87
}

This creates a student dictionary with four key-value pairs.

🎯 Accessing Values

Use the key inside square brackets or the .get() method.

print(student["name"])   # Output: Aarav
print(student.get("marks"))  # Output: 87

➕ Adding New Items

student["school"] = "Tapasvi School"
print(student)

🔁 Updating a Value

student["marks"] = 92

❌ Removing Items

del student["class"]  # Removes the "class" key-value pair

Or:

student.pop("age")

📚 Useful Dictionary Methods

Method Description
dict.keys() Returns a list of all keys
dict.values() Returns a list of all values
dict.items() Returns key-value pairs as tuples
dict.update() Adds or updates items from another dict
dict.clear() Empties the dictionary

Example:

print(student.keys())    # dict_keys(['name', 'marks', 'school'])
print(student.values())  # dict_values(['Aarav', 92, 'Tapasvi School'])

🔄 Looping Through a Dictionary

Loop through keys:

for key in student:
    print(key)

Loop through keys and values:

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

🧠 Nested Dictionaries

A dictionary can contain another dictionary. This is useful when storing complex data.

Example:

class_data = {
    "student1": {"name": "Riya", "marks": 90},
    "student2": {"name": "Aman", "marks": 85}
}

To access Riya's marks:

print(class_data["student1"]["marks"])  # Output: 90

✅ When to Use a Dictionary

Use a dictionary when:

  • You want to store pairs (like ID–name, product–price, etc.)
  • You need quick access to a value using a key
  • Order doesn't matter (though in Python 3.7+, order is preserved)

🔚 Summary

  • A dictionary holds key-value pairs.
  • Keys must be unique and immutable (strings, numbers, etc.)
  • Values can be anything (numbers, strings, lists, even other dictionaries)
  • Great for organized and structured data

No comments:

Post a Comment

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...