Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • Tags
  • Connexion

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)
3 months ago Permalien
cluster icon
  • Working with CSV files : Working with CSV files CSV (Comma Separated Values) is a plain-text tabular format where each line is a row and fields are delimited (commonly by com...
  • Python Modules and the import System : Python Modules and the import System What is a Module? A module in Python corresponds directly to a single file containing Python code. The module's ...
  • Functions, Docstrings : Functions Functions package reusable code into named blocks, improving modularity, readability, and testability. They prevent duplication (DRY) and ma...
  • Automated Testing with Pytest : Assertions in Pytest Pytest uses Python’s built-in assert statement to declare expected conditions in tests, making test code concise and readable. W...
  • Typing : Introduction Python is a dynamically typed language, meaning you can assign values to variables without declaring their types, and type checking happ...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli