techmore.in

Python - Dictionaries

A dictionary in Python is a collection of key-value pairs. It is unordered, mutable, and indexed by unique keys.

Dictionaries are useful when you want to associate a value with a key, such as storing information like name and age together.

They are defined using curly braces {} with key-value pairs separated by a colon :.

Use dictionaries when you want fast lookups with unique keys.

Creating a Dictionary

python
# Creating a dictionary
student = {
    "name": "Alice",
    "age": 22,
    "course": "Python"
}
print(student)

Accessing Elements

python
print(student["name"])     # Alice
print(student.get("age"))  # 22

Modifying Elements

python
student["age"] = 23
student["grade"] = "A"
print(student)

Removing Elements

python
student.pop("grade")       # Removes the grade key
print(student)

Looping Through Dictionary

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

Pros and Cons

  • Pros: Fast access, flexible value types, dynamic size
  • Cons: Keys must be hashable and unique, unordered before Python 3.7

Summary

Dictionaries are essential in Python for mapping keys to values. They are fast and flexible, making them ideal for many programming tasks like configurations, lookups, and data grouping.