Python Dictionnaries
Python Dictionaries
Dictionaries are one of the most powerful and flexible data types in Python. They allow you to store and organize data using key-value pairs, making it easy to access and modify values based on a specific identifier.
What is a Dictionary?
A dictionary in Python is a collection of unordered, changeable, and indexed data. Unlike lists or tuples that use numerical indexes, dictionaries use keys to access their corresponding values.
Syntax:
my_dict = {
"key1": "value1",
"key2": "value2"
}
- Keys must be unique and immutable (like strings or numbers).
- Values can be of any data type and can be duplicated.
Creating a Dictionary
Here’s how you can define a dictionary:
person = {
"name": "Alice",
"age": 30,
"city": "Paris"
}
You can also use the dict()
constructor:
person = dict(name="Alice", age=30, city="Paris")
Accessing Values
To get the value of a specific key, use square brackets or the .get()
method:
print(person["name"]) # Output: Alice
print(person.get("age")) # Output: 30
[]
raises an error if the key doesn’t exist..get()
returnsNone
(or a default value if provided) when the key is missing.
Adding and Updating Entries
You can add a new key-value pair or update an existing one:
person["email"] = "alice@example.com" # Add new key
person["age"] = 31 # Update existing key
Output:
{'name': 'Alice', 'age': 31, 'city': 'Paris', 'email': 'alice@example.com'}
Removing Entries
Python offers several ways to remove items from a dictionary:
del
keyword.pop()
method.popitem()
method
del person["city"]
print(person)
email = person.pop("email")
print(email)
last_item = person.popitem() # Removes the last inserted pair
print(last_item)
Checking if a Key Exists
Use the in
keyword to check if a key is present:
if "name" in person:
print("Name is defined")
Iterating Over a Dictionary
You can loop through keys, values, or both:
# Keys
for key in person:
print(key)
# Values
for value in person.values():
print(value)
# Key-Value pairs
for key, value in person.items():
print(f"{key} : {value}")
Dictionary Length
Use len()
to get the number of key-value pairs:
print(len(person)) # Output: 2
Nested Dictionaries
A dictionary can contain another dictionary:
users = {
"alice": {"age": 30, "email": "alice@example.com"},
"bob": {"age": 25, "email": "bob@example.com"}
}
print(users["alice"]["email"])
Output:
alice@example.com
Summary
- A dictionary stores data using key-value pairs.
- Keys must be unique and immutable.
- Values can be of any type.
- You can easily add, update, delete, and iterate over items.
- They are perfect for structured data and quick lookups.
Dictionaries are an essential part of Python and mastering them will unlock more advanced programming techniques.
Continue Learning
Python Variables
Popular
### Understanding Variables and Literals in Python Variables and literals are the foundation of any
Personalized Recommendations
Log in to get more relevant recommendations based on your reading history.