Home > Article > Backend Development > Here are a few question-style titles based on your provided article: Direct and Focused: * Frozen Dicts in Python: A Feasible Concept? * Can Python Dictionaries Be Truly Immutable? * Is There a \&qu
Python offers immutable collections like frozen sets and tuples. Could there exist a similar concept for dictionaries known as a "frozen dict"?
The primary motivation for creating such a data structure lies in its utility for memoizing functions with dynamic arguments. Typically, the hashable equivalent of a dict is stored as a sorted tuple containing the key-value pairs of the input dict. However, Python does not guarantee a specific sorting order, potentially causing discrepancies.
A custom wrapper can be implemented to mimic the behavior of a frozen dict, adhering to Python's mapping protocol. Here's an example:
<code class="python">import collections class FrozenDict(collections.Mapping): def __init__(self, *args, **kwargs): self._d = dict(*args, **kwargs) self._hash = None # Implement methods inherited from collections.Mapping # ... def __hash__(self): # Calculate the hash on demand to optimize performance if self._hash is None: h = 0 for pair in self.items(): h ^= hash(pair) self._hash = h return self._hash</code>
This custom data structure behaves similarly to a standard dictionary, allowing access to keys, values, and iteration. It also supports checks for membership and equality, and it functions properly as a key in other dictionaries.
The above is the detailed content of Here are a few question-style titles based on your provided article: Direct and Focused: * Frozen Dicts in Python: A Feasible Concept? * Can Python Dictionaries Be Truly Immutable? * Is There a \&qu. For more information, please follow other related articles on the PHP Chinese website!