Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Dictionaries/shaare/xQcXjQ

  • python
  • python

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(), and my_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 with my_dictionary.popitem().
  • Merging: Combine dictionaries using the | operator (Python 3.9+) or update() 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 key
  • server_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)
2 months ago Permalink
cluster icon
  • Adding Type Hints to Decorators and Generators : Adding Type Hints to Decorators and Generators Decorators and generators are advanced constructs that require specialized type hints to make their tr...
  • Python package and subpackage : Introduction to Packages (__init__.py) What is a Package? A Python package provides a way to structure a project's module namespace by using directori...
  • Functions: return vs yield : Functions: return vs yield Regular functions execute immediately, run to completion, and return a single value (or None). Generator functions retur...
  • The Iteration Protocol : The Iteration Protocol We use for item in sequence: all the time. But how does Python get each item? Iterable: An object that can be looped over. It...
  • Numbers, strings : Numbers (int and float) int: Whole numbers (e.g., 10, 1024). No overflow due to arbitrary precision. float: Numbers with decimals (e.g., 3.14159). Us...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community