Python Dictionary Data Type
In Python, a Dictionary is a mapping data type that stores data in key and value pairs. Dictionaries are defined using curly braces {}
, and each element consists of a key and a value. For example:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
Features of Dictionary
1. Stored in Key-Value Pairs
Dictionaries store each element as a key-value pair, and keys must be unique. Keys must be immutable types (e.g., strings, numbers, tuples), while values can be of any data type.
person = {"name": "Bob", "age": 30, "job": "Developer"}
print(person["name"]) # 'Bob'
print(person["age"]) # 30
2. Modifying Dictionaries
Dictionaries are mutable, which means you can add, modify, or delete elements. You can add new key-value pairs or modify existing values.
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "New York" # Add a new key-value pair
my_dict["age"] = 26 # Modify existing value
print(my_dict) # {'name': 'Alice', 'age': 26, 'city': 'New York'}
3. Deleting Dictionary Elements
You can delete a specific element from a dictionary using the del
keyword or the pop()
method.
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
del my_dict["age"] # Delete 'age' key
print(my_dict) # {'name': 'Alice', 'city': 'New York'}
city = my_dict.pop("city") # Delete 'city' key and return its value
print(city) # 'New York'
print(my_dict) # {'name': 'Alice'}
4. Dictionary Methods
Dictionaries provide various methods for easy manipulation of elements:
dict.keys()
: Returns all keys in the dictionary.dict.values()
: Returns all values in the dictionary.dict.items()
: Returns all key-value pairs as tuples.dict.get(key)
: Returns the value corresponding to the key; returnsNone
if the key does not exist.dict.update(other_dict)
: Adds or updates elements from another dictionary.
my_dict = {"name": "Alice", "age": 25}
print(my_dict.keys()) # dict_keys(['name', 'age'])
print(my_dict.values()) # dict_values(['Alice', 25])
print(my_dict.items()) # dict_items([('name', 'Alice'), ('age', 25)])
print(my_dict.get("city")) # None
my_dict.update({"city": "New York", "age": 26})
print(my_dict) # {'name': 'Alice', 'age': 26, 'city': 'New York'}
5. Iterating Over Dictionaries
You can use loops to iterate over keys, values, or key-value pairs in a dictionary.
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Iterating over keys
for key in my_dict:
print(key)
# Iterating over values
for value in my_dict.values():
print(value)
# Iterating over key-value pairs
for key, value in my_dict.items():
print(f"{key}: {value}")
6. Nested Dictionaries
Dictionaries can have other dictionaries as values, which are called nested dictionaries. Nested dictionaries are useful for structuring complex data.
nested_dict = {
"person1": {"name": "Alice", "age": 25},
"person2": {"name": "Bob", "age": 30}
}
print(nested_dict["person1"]["name"]) # 'Alice'
print(nested_dict["person2"]["age"]) # 30
Summary
- Dictionaries are a mapping data type that stores data in key-value pairs.
- Dictionaries are mutable and allow adding, modifying, and deleting elements.
- Methods like
keys()
,values()
,items()
allow access to dictionary elements. - Dictionaries can be iterated over with loops to access keys, values, or key-value pairs.
- Nested dictionaries can be used to structure complex data.
Dictionaries are one of the most important data types in Python, useful for efficiently storing and manipulating data. Explore the various features of dictionaries to handle complex data!