Using a Python Dictionary as a Key (Non-nested)
If you have a really immutable dictionary (although it isn't clear to me why you don't just use a list of pairs: e.g. [('content-type', 'text/plain'), ('host', 'example.com')]
), then you may convert your dict
into:
A tuple of pairs. You've already done that in your question. A
tuple
is required instead oflist
because the results rely on the ordering and the immutability of the elements.>>> tuple(sorted(a.items()))
A frozen set. It is a more suitable approach from the mathematical point of view, as it requires only the equality relation on the elements of your immutable
dict
, while the first approach requires the ordering relation besides equality.>>> frozenset(a.items())
If I needed to use dictionaries as keys, I would flatten the dictionary into a tuple of tuples.
You might find this SO question useful: What is the best way to implement nested dictionaries?
And here is an example of a flatten module that will flatten dictionaries: http://yawpycrypto.sourceforge.net/html/public/Flatten.Flatten-module.html
I don't fully understand your use case and I suspect that you are trying to prematurely optimize something that doesn't need optimization.