Master Python Dictionaries: Tips, Tricks, and Best Practices
Explore the power of immutable sequences with Python tuples. Discover tips, tricks, and common uses to optimize your code.
Dict: A Python dictionary (dict) is an unordered collection of items. Each item is a key-value pair, where keys are unique within a dictionary and are used to store and retrieve values.
# Dictionary with initial key-value pairs
car_details = {"brand": "Ford", "model": "Mustang", "year": 1964}
Removing a key and retrieving its value:
car_details = {"brand": "Ford", "model": "Mustang", "year": 1964}
year = car_details.pop("year")
print(year) # Output: 1964
Merging Dictionaries:
car_details = {"brand": "Ford", "model": "Mustang"}
car_details2 = {"year": 1964}
merged_dict = car_details | car_details2
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Sorting a Dictionary:
# Sorting by keys
sorted_by_keys = dict(sorted(car_details.items()))
# Sorting by values (let's say by the length of values for this example)
sorted_by_values = dict(sorted(car_details.items(), key=lambda item: len(str(item[1]))))
Dictionary Unpacking:
def show_car_details(model, year):
print(f"Model: {model} and Year: {year}")
car_info = {"model": "Mustang", "year": 1964}
show_car_details(**car_info)
# Output: "Model: Mustang and Year: 1964"
Immutable Dictionary with types.MappingProxyType
:
from types import MappingProxyType
car_details = {"model": "Mustang", "year": 1964}
# Immutable version of a Dictionary
immutable_car_details = MappingProxyType(car_details)
immutable_car_details["color"] = "Red"
# This would raise a TypeError
The `setdefault()` method:
The
setdefault
method in a Python dictionary is used to retrieve the value of a specified key if it exists. If the key doesn't exist, it inserts the key with a specified default value and then returns that default value.
# General syntax:
dict.setdefault(key, default_value)
Retrieving an existing key:
car_details = {"model": "Mustang", "year": 1964}
model = car_details.setdefault("model", "Bronco")
print(model)
# Output: "Mustang"
print(car_details)
# Output: {'model': 'Mustang', 'year': 1964}
Adding a new key with default value:
car_details = {"model": "Mustang", "year": 1964}
color = car_details.setdefault("color", "Red")
print(color)
# Output: "Red"
print(car_details)
# Output: {'model': 'Mustang', 'year': 1964, 'color': 'Red'}
These tricks should help you get the most out of Python dictionaries, enhancing both your efficiency and the readability of your code!