Python Dictionary: From Basics to Advanced Usage
Python Dictionary: From Basics to Advanced Usage ๐
A dictionary in Python is a powerful data structure that stores key-value pairs.
In this post, we'll dive into everything you need to know—from basic operations to advanced techniques.
✅ Creating a Basic Dictionary
Use curly braces {} to define a dictionary with keys and values.
# Creating a basic dictionary
student = {"name": "John", "age": 21, "major": "Computer Science"}
print(student)
✅ Accessing and Modifying Values
You can retrieve or update a value by using its key.
# Accessing and modifying values
print(student["name"]) # John
student["age"] = 22 # Update age
print(student)
✅ Using Dictionary Methods
Access keys, values, or key-value pairs easily with built-in methods like keys(), values(), and items().
# Using dictionary methods
print(student.keys()) # All keys
print(student.values()) # All values
print(student.items()) # Key-value pairs
✅ Dictionary Comprehension
Create new dictionaries in a single line using dictionary comprehensions.
# Dictionary comprehension
squared_numbers = {x: x**2 for x in range(5)}
print(squared_numbers) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Dictionaries are widely used in JSON processing, configuration files, data mapping, and more. Building a solid understanding now will pay off greatly in real-world projects!
The better you manage data, the better you solve problems. Small improvements today lead to major breakthroughs tomorrow. ๐
Icons by Flaticon
Comments
Post a Comment