site logo

Learn to Python. Build the Future.


Category: (All)
❮  Go Back

15. Mastering Python Dictionaries: A Comprehensive Guide

Introduction

In Python, dictionaries are unordered collections of key-value pairs. They are mutable, allowing for the storage and retrieval of data using unique keys. Understanding how to work with dictionaries is essential for effective Python programming.


Creating Dictionaries

You can create a dictionary by placing comma-separated key-value pairs inside curly braces:

person = {"name": "Alice", "age": 30, "city": "New York"}

Alternatively, use the dict() constructor:

person = dict(name="Alice", age=30, city="New York")


Accessing Dictionary Items

You can access the value associated with a specific key using square brackets:

print(person["name"]) # Output: Alice

To avoid errors if the key doesn't exist, use the get() method:

print(person.get("age", "Not Found")) # Output: 30


Changing Dictionary Items

To change the value of an existing key, assign a new value:

person["age"] = 31

To add a new key-value pair:

person["email"] = "alice@example.com"


Removing Items

You can remove a key-value pair using the del statement:

del person["email"]

Alternatively, use the pop() method to remove a key and return its value:

email = person.pop("email", "Not Found")

To remove all items:

person.clear()


Looping Through a Dictionary

You can loop through a dictionary's keys:

for key in person:
print(key)

To loop through keys and values:

for key, value in person.items():
print(key, value)


Copying a Dictionary

To create a shallow copy of a dictionary:

person_copy = person.copy()

To create a copy using the dict() constructor:

person_copy = dict(person)


Nested Dictionaries

Dictionaries can contain other dictionaries:

employees = {
"emp1": {"name": "Alice", "age": 30},
"emp2": {"name": "Bob", "age": 25}
}

Accessing nested dictionary values:

print(employees["emp1"]["name"]) # Output: Alice


Dictionary Methods

Python provides several built-in methods for dictionaries:

  1. clear(): Removes all items from the dictionary.
  2. copy(): Returns a shallow copy of the dictionary.
  3. get(key, default): Returns the value for key if key is in the dictionary; otherwise, returns default.
  4. items(): Returns a view object that displays a list of a dictionary's key-value tuple pairs.
  5. keys(): Returns a view object that displays a list of all the keys in the dictionary.
  6. pop(key, default): Removes the specified key and returns the corresponding value. If the key is not found, returns default.
  7. popitem(): Removes and returns an arbitrary (key, value) pair.
  8. setdefault(key, default): Returns the value of key if key is in the dictionary; if not, inserts key with a value of default and returns default.
  9. update(other): Updates the dictionary with the key-value pairs from other, overwriting existing keys.
  10. values(): Returns a view object that displays a list of all the values in the dictionary.


Conclusion

Dictionaries are a powerful data structure in Python, allowing for efficient storage and retrieval of data using unique keys. By understanding how to create, access, modify, remove, loop through, copy, nest, and utilize dictionary methods, you can effectively manage collections of data in your Python programs.

15. Mastering Python Dictionaries A Comprehensive Guide

coldshadow44 on 2025-10-08



(0)





Showing comments related to this post.




Member's Sites: