Dictionaries/shaare/xQcXjQ
Dictionaries (dict)
Dictionaries are mutable, insertion-ordered collections of key-value pairs. Keys must be unique and immutable; values can be of any type.
Characteristics and Use Cases
- Insertion-ordered (Python 3.7+)
- Mutable: add, remove, or change key-value pairs
- Fast lookups by key
- Ideal for configuration data, JSON-like structures, and lookups
Dictionary Operations Overview
Dictionaries in Python support a variety of operations for efficient data manipulation:
- Length: Use
len(my_dictionary)to get the number of key-value pairs. - Accessing Keys, Values, and Items: Use
my_dictionary.keys(),my_dictionary.values(), andmy_dictionary.items()to retrieve keys, values, or key-value pairs. - Membership Test: Check if a key exists using
'key' in my_dictionary. - Get with Default: Use
my_dictionary.get('key', default)to safely retrieve a value with a fallback. - Setdefault: Add a key with a default value if it doesn't exist using
my_dictionary.setdefault(key, default). - Pop and Popitem: Remove a specific key with
my_dictionary.pop(key)or remove an arbitrary key-value pair withmy_dictionary.popitem(). - Merging: Combine dictionaries using the
|operator (Python 3.9+) orupdate()method. - Fromkeys: Create a new dictionary with specified keys and a default value using
dict.fromkeys(keys, value). - Clear: Remove all items from the dictionary with
my_dictionary.clear().
my_dictionary = {'a': 1, 'b': 2, 'c': 3}
print(my_dictionary)
print(f"Length: {len(my_dictionary)}")
# Keys, Values, and Items
print(f"Keys: {my_dictionary.keys()}")
print(f"Values: {my_dictionary.values()}")
print(f"Items: {my_dictionary.items()}")
for item in my_dictionary.items():
print(type(item))
for key, value in my_dictionary.items():
print(f"- {key}: {value}")
# Membership test
print(f"'b' is in my_dictionary? {"b" in my_dictionary}")
print(f"'d' is in my_dictionary? {"d" in my_dictionary}")
print(f"1 is in my_dictionary? {1 in my_dictionary}")
print(f"1 is in values of my_dictionary? {1 in set(my_dictionary.values())}")
# Accessing elements
print("'b':", my_dictionary["b"]) # Will raise KeyError if key is not present in the dictionary
print("'b':", my_dictionary.get("b")) # Will not raise KeyError
print("'e' without default:", my_dictionary.get("e"))
print("'e' with default:", my_dictionary.get("e", -1))
my_dictionary.setdefault("d", 4)
print(my_dictionary)
# Removing elements
removed = my_dictionary.pop("a")
print(f"Removed value: {removed}")
removed = my_dictionary.popitem()
print(f"Removed value: {removed}")
removed = my_dictionary.popitem()
print(f"Removed value: {removed}")
# Merging of dictionaries
default_tags = {
"Environment": "Production",
"Owner": "Finance",
"CostCenter": "10000"
}
custom_tags = {
"CostCenter": "12345"
}
merged_tags = default_tags | custom_tags
print(merged_tags)
default_tags.update(custom_tags)
print(default_tags)
# Creating new dictionary based on a set of keys
new_dict = dict.fromkeys(['one', 'two', 'one'], 0)
print(new_dict)
new_dict.clear()
print(new_dict)
Adding and Updating Items
server_config['port'] = 8080# Update existing keyserver_config['environment'] = 'production'# Add new key-value pair
tags = {
"Environment": "Production",
"Owner": "Finance",
"CostCenter": "10000"
}
tags["CostCenter"] = "12345"
tags["Project"] = "Python for DevOps"
print(tags)
(97)