Python Dictionaries are one of the most powerful and flexible built-in data types in Python. They provide a way to store data in key-value pairs, making it easy to access, update, and manipulate structured information efficiently. Dictionaries are widely used in real-world applications, from configuration settings to storing user data and mapping relationships.
A Python Dictionary is an unordered, mutable collection of items. Each item is a pair of a key and its corresponding value. Keys must be unique and immutable (such as strings, numbers, or tuples), while values can be of any data type.
# Creating a dictionary person = { "name": "Alice", "age": 30, "city": "New York" } print(person["name"]) # Output: Alice
In this example, the dictionary person contains three key-value pairs, and you can retrieve values by referencing their keys.
# Using curly braces d1 = {"a": 1, "b": 2} # Using dict() constructor d2 = dict(x=10, y=20) # Using a list of tuples d3 = dict([("name", "Bob"), ("age", 25)]) # Empty dictionary empty = {}
person = {"name": "Tom", "age": 22} # Accessing value print(person["age"]) # Output: 22 # Modifying value person["age"] = 23 # Adding a new key-value pair person["city"] = "London"
| Method | Description | Example |
|---|---|---|
| keys() | Returns all keys | person.keys() |
| values() | Returns all values | person.values() |
| items() | Returns key-value pairs | person.items() |
| get() | Returns value for key, or default | person.get("name") |
| update() | Updates dictionary with key-value pairs | person.update({"age": 35}) |
| pop() | Removes item with given key | person.pop("city") |
user = {"name": "Eva", "role": "admin", "status": "active"} # Loop through keys for key in user: print(key) # Loop through values for value in user.values(): print(value) # Loop through key-value pairs for key, value in user.items(): print(key, ":", value)
You can nest dictionaries within dictionaries for complex data structures.
students = { "student1": {"name": "Alice", "age": 21}, "student2": {"name": "Bob", "age": 22} } print(students["student1"]["name"]) # Output: Alice
| Feature | Dictionaries | Lists |
|---|---|---|
| Storage | Key-value pairs | Sequential items |
| Access | Accessed by key | Accessed by index |
| Order (Python 3.7+) | Maintains insertion order | Maintains insertion order |
| Use Case | Lookup operations | Ordered data storage |
Python Dictionaries are an indispensable part of Python programming. Their flexibility and efficiency in handling key-value data make them ideal for a wide variety of tasks. Mastering dictionaries will improve your ability to write clean, fast, and functional Python code that can handle structured data with ease.
Copyrights © 2024 letsupdateskills All rights reserved