def dict(iterable: Optional[Iterable], /, **kwargs: Any) -> DictObject
Creates a persistent, mutable mapping object, analogous to Python's built-in dict.
Keys must be hashable, just like in a standard Python dict. This includes types like strings, numbers and tuples (if their elements are hashable). Values can be of any type, including other dbzero collections.
In addition to regular types, dbzero.dict also supports the use of dbzero.memo objects and dbzero.enum values as keys. In case of memo objects, an instance UUID is used as a mapping key. It means that in a lookup you have to use the exact same memo object.
Familiar API: This class is designed as a persistent counterpart to Python's built-in collection. It implements the same interface and supports all standard operations, allowing you to use it easily as a drop-in replacement while providing automatic persistance.
Parameters
-
iterableIterable, optional
Mapping object or iterable of key-value pairs. -
**kwargsAny
Initialize dictionary with keyword arguments.
Returns
A new dbzero.dict object.
Examples
Creating a dictionary
You can create a dbzero.dict in several ways, just like a regular dict.
# Create an empty dictionary
d1 = db0.dict()
# Create from keyword arguments
d2 = db0.dict(name="Alice", age=30)
print(d2["name"]) # Outputs: Alice
# Create from a list of tuples
d3 = db0.dict([("name", "Bob"), ("age", 25)])
print(d3["age"]) # Outputs: 25
# Create from another dictionary
d4 = db0.dict({"name": "Charlie", "age": 35})
print(d4) # Outputs: {'name': 'Charlie', 'age': 35}Basic operations
dbzero.dict supports all the fundamental dictionary operations.
data = db0.dict(name="Alice", age=30)
# Access an item
print(data["name"]) # Outputs: Alice
# Add or update an item
data["city"] = "New York"
data["age"] = 31
# Check for a key's existence
if "city" in data:
print("City is present.")
# Delete an item
del data["age"]
assert "age" not in data
# Get the number of items
print(len(data)) # Outputs: 2Using memo objects and enum values as keys
dbzero.dict can use memo objects and enum values as keys. Memo objects are identified by their UUID.
# Create a memo class
@db0.memo
class User:
def __init__(self, name):
self.name = name
# Create an enum
Status = db0.enum("Status", ["ACTIVE", "INACTIVE", "PENDING"])
# Using memo objects as keys
user1 = User("Alice")
user2 = User("Bob")
user_scores = db0.dict()
user_scores[user1] = 100
user_scores[user2] = 85
# Lookup requires the same instance
print(user_scores[user1])
# Expected output: 100
# Using enum values as keys
status_counts = db0.dict()
status_counts[Status.ACTIVE] = 42
status_counts[Status.PENDING] = 8
status_counts[Status.INACTIVE] = 5
print(status_counts[Status.ACTIVE])
# Expected output: 42
# Using tuple with memo object as composite key
stats = db0.dict()
stats[(user1, "logins")] = 15
stats[(user1, "last_login")] = "2024-01-15"
stats[(user2, "logins")] = 23
print(stats[(user1, "logins")])
# Expected output: 15