Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Dictionaries

A dictionary in Python is a collection of key-value pairs. It is unordered, mutable, and does not allow duplicate keys. Dictionaries are useful for storing data in key-value format, making lookups fast and efficient.

1. Creating a Dictionary

You can create a dictionary using curly braces {} or the dict() function.

# Creating a dictionary using curly braces
student = {
    "name": "John",
    "age": 22,
    "course": "Computer Science"
}
print(student)

# Creating a dictionary using dict()
person = dict(name="Bob", age=25, city="New York")
print(person)

Key Points:

  • Each key must be unique.
  • Values can be of any data type (int, string, list, another dictionary, etc.).
  • Keys must be immutable (strings, numbers, or tuples but not lists).

2. Accessing Dictionary Elements

You can access values using square brackets [] or the .get() method.

student = {"name": "John", "age": 22, "course": "Computer Science"}

# Accessing using key
print(student["name"])  # Output: John

# Using .get() method (avoids error if key is missing)
print(student.get("age"))  # Output: 22
print(student.get("city", "Not Found"))  # Output: Not Found

Why use .get()?

  • If a key does not exist, student["city"] gives an error, but student.get("city") returns None (or a default value).

3. Adding & Updating Dictionary Items

You can add or modify dictionary values by assigning a value to a key.

# Adding a new key-value pair
student["city"] = "New York"
print(student)  # {'name': 'John', 'age': 22, 'course': 'Computer Science', 'city': 'New York'}

# Updating an existing key
student["age"] = 23
print(student)  # {'name': 'John', 'age': 23, 'course': 'Computer Science', 'city': 'New York'}

4. Removing Elements from a Dictionary

You can remove key-value pairs using del, pop(), or popitem().

student = {"name": "John", "age": 22, "course": "Computer Science"}

# Using del (removes key permanently)
del student["age"]
print(student)  # {'name': 'John', 'course': 'Computer Science'}

# Using pop() (removes and returns the value)
course = student.pop("course")
print(course)  # Output: Computer Science
print(student)  # {'name': 'John'}

# Using popitem() (removes the last inserted item)
student["city"] = "New York"
student.popitem()
print(student)  # {'name': 'John'}

Difference between pop() and del:

  • pop("key") returns the removed value.
  • del dictionary["key"] deletes without returning anything.

5. Dictionary Methods

Here are some useful dictionary methods:

Method	Description
dict.keys()	Returns all keys
dict.values()	Returns all values
dict.items()	Returns key-value pairs as tuples
dict.update(new_dict)	Merges two dictionaries
dict.pop("key")	Removes a key and returns its value
dict.popitem()	Removes and returns the last key-value pair
dict.clear()	Removes all elements

Example:

student = {"name": "John", "age": 22, "course": "Computer Science"}

# Getting all keys
print(student.keys())  # dict_keys(['name', 'age', 'course'])

# Getting all values
print(student.values())  # dict_values(['John', 22, 'Computer Science'])

# Getting all key-value pairs
print(student.items())  # dict_items([('name', 'John'), ('age', 22), ('course', 'Computer Science')])

6. Iterating Through a Dictionary

You can loop through a dictionary to access keys, values, or both.

student = {"name": "John", "age": 22, "course": "Computer Science"}

# Loop through keys
for key in student:
    print(key)  # name, age, course

# Loop through values
for value in student.values():
    print(value)  # John, 22, Computer Science

# Loop through key-value pairs
for key, value in student.items():
    print(f"{key}: {value}")

Best practice: Use .items() to access both keys and values in a loop.

7. Merging Dictionaries (update())

You can combine two dictionaries using the .update() method.

dict1 = {"name": "John", "age": 22}
dict2 = {"city": "New York", "age": 23}  # Overwrites 'age' key

dict1.update(dict2)
print(dict1)  # {'name': 'John', 'age': 23, 'city': 'New York'}

✅ If a key exists in both dictionaries, .update() overwrites it.

8. Dictionary Comprehension

You can create dictionaries dynamically using dictionary comprehension.

squares = {x: x*x for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Useful when creating dictionaries dynamically.

9. Nested Dictionaries

A dictionary can have another dictionary as its value.

students = {
    "Alice": {"age": 22, "course": "CS"},
    "Bob": {"age": 23, "course": "Math"}
}

print(students["John"]["course"])  # Output: CS

Used for storing structured data (like JSON objec

    Leave a Reply

    Your email address will not be published.

    Need Help?