Python Dictionary (dict)

A complete guide to understanding Python's dictionary data type

📌 What is a Dictionary?

Dict in Detail

A dictionary in Python is a collection of key-value pairs. It works like a real-life dictionary: you use a key (the word) to find its value (the meaning).

📝 Creating a Dictionary


# Empty dictionary
my_dict = {}

# Dictionary with data
student = {
    "name": "Alice",
    "age": 21,
    "course": "Computer Science"
}

print(student["name"])   # Alice
print(student["age"])    # 21
      

⚡ Accessing and Modifying Data


student = {"name": "Alice", "age": 21}

# Access value
print(student["name"])   # Alice

# Add new key-value pair
student["course"] = "Python"

# Modify existing value
student["age"] = 22

# Delete a key-value pair
del student["name"]

print(student)  # {'age': 22, 'course': 'Python'}
      

🛠️ Dictionary Methods

Here are the most commonly used dictionary methods:

Method Description Example
dict.keys() Returns all keys student.keys()
dict.values() Returns all values student.values()
dict.items() Returns key-value pairs as tuples student.items()
dict.get(key) Gets value safely (returns None if missing) student.get("age")
dict.pop(key) Removes and returns a value student.pop("age")
dict.update() Updates dictionary with new data student.update({"age": 23})
dict.clear() Removes all items student.clear()
dict.copy() Returns a shallow copy student.copy()
dict.fromkeys() Creates dict from keys with same value dict.fromkeys(["a","b"], 0)
dict.setdefault() Returns value if exists, else inserts default student.setdefault("grade","A")

📚 Nested Dictionaries

Dictionaries can contain other dictionaries, useful for structured data:


students = {
    "student1": {"name": "Alice", "age": 21},
    "student2": {"name": "Bob", "age": 22}
}

print(students["student1"]["name"])  # Alice
print(students["student2"]["age"])   # 22
      

🎯 Uses of Dictionary


# Example: Counting character frequency
text = "banana"
freq = {}

for char in text:
    freq[char] = freq.get(char, 0) + 1

print(freq)  # {'b': 1, 'a': 3, 'n': 2}
      

🔑 Key Points to Remember