Tuesday, August 26, 2025

🐍DICTINARIES IN PYTHON

Dictionaries are key-value pairs that allow you to store and access data efficiently using unique keys.

1) What is a Dictionary?

A dictionary is an unordered collection of items where each item is a key-value pair. Keys must be unique and immutable (like strings, numbers, or tuples), while values can be any type, including lists or other dictionaries.


# Example
person = {
    "name": "Alice",
    "age": 25,
    "city": "London"
}

empty_dict = {}
nested_dict = {
    "student1": {"name": "Bob", "age": 20},
    "student2": {"name": "Charlie", "age": 22}
}

2) Accessing Values

Access values using their keys.


person = {"name": "Alice", "age": 25, "city": "London"}

print(person["name"])   # Alice
print(person.get("age")) # 25

Note: Using a non-existing key with square brackets raises KeyError, but get() returns None or a default value.

3) Adding and Updating Items


person = {"name": "Alice", "age": 25}

# Add new key-value
person["city"] = "London"

# Update existing key
person["age"] = 26

print(person)
# Output: {'name': 'Alice', 'age': 26, 'city': 'London'}

4) Removing Items


person = {"name": "Alice", "age": 25, "city": "London"}

# Remove by key
del person["city"]

# Remove and return value
age = person.pop("age")

# Clear entire dictionary
person.clear()

print(person)
# Output: {}

5) Iterating through Dictionaries


person = {"name": "Alice", "age": 25, "city": "London"}

# Iterate keys
for key in person:
    print(key)

# Iterate values
for value in person.values():
    print(value)

# Iterate key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

6) Common Dictionary Methods

  • get(key, default) – Access value safely
  • keys() – Returns all keys
  • values() – Returns all values
  • items() – Returns all key-value pairs
  • update() – Merge another dictionary
  • pop(key) – Remove and return value
  • clear() – Remove all items

7) Common Mistakes

  • Using mutable types as keys (lists, dictionaries) → TypeError
  • Accessing non-existent keys without get()KeyError
  • Confusing keys and values when iterating
  • Modifying dictionary size while iterating → unexpected behavior

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??