Python Dictionaries: Key-Value Pairs Explained

Python programming tutorial

Python Dictionaries: Key-Value Pairs Explained

Beginner

Dictionaries are Python's versatile mapping type, storing data in key-value pairs for efficient retrieval.

Core Concept

Dictionaries are unordered collections of items. Each item is a key-value pair. Keys must be unique and immutable (e.g., strings, numbers, tuples).

Basic Example

Basics.py

# Creating a dictionary
student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Accessing values by key
print(student["name"])  # Output: Alice
print(student.get("age")) # Output: 20

# Adding a new key-value pair
student["gpa"] = 3.8
print(student)
# Output: {'name': 'Alice', 'age': 20, 'major': 'Computer Science', 'gpa': 3.8}

  

How It Works

You create dictionaries using curly braces `{}` with key:value pairs separated by commas. Access values using square brackets `[]` or the `.get()` method. You can add or modify items by assigning values to keys.

Advanced Example

advance.py

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Iterating through a dictionary
for key, value in squares.items():
    print(f"Key: {key}, Value: {value}")

# Removing items
del squares[2]
print(squares)
# Output: {0: 0, 1: 1, 3: 9, 4: 16}

  

Common Use Cases

  • Storing configuration settings.
  • Representing JSON data.
  • Counting item frequencies.
  • Implementing caches.

Common Pitfalls

  • Using mutable objects (like lists) as keys.
  • Forgetting that dictionaries are unordered in older Python versions (pre-3.7).
  • Trying to access a non-existent key without using `.get()` or checking existence.

Related Tutorials

Mastering Modern Python: Top Trending Lessons for 2024 Success
Master the Future: Top Trending Python Lessons & Skills for 2024
Mastering Ethical AI in Python: Top Trending Lessons for 2026
Python Type Hinting with Pydantic for Robust Data Validation
Python Structural Pattern Matching: The `match` Statement

FAQs

Q: How do I check if a key exists in a dictionary?
A: Use the `in` operator: `if 'key' in my_dict:`. Or use `.get()` with a default value: `value = my_dict.get('key', 'default_value')`.

Q: Can dictionary keys be lists?
A: No, keys must be immutable. Lists are mutable.

Q: What is the difference between `.keys()`, `.values()`, and `.items()`?
A: `.keys()` returns a view object of all keys. `.values()` returns a view object of all values. `.items()` returns a view object of key-value tuple pairs.

Conclusion

Dictionaries are fundamental to Python programming, providing an efficient and flexible way to manage data through key-value associations.

Comments

Popular posts from this blog

Python Structural Pattern Matching: The `match` Statement

Python Structural Pattern Matching: The `match` Statement

Python Dictionaries: Key-Value Pairs for Efficient Data Mapping