6 ms·
I'm piqued by one thing in this article. Using an object as a dictionary key. What's the use for that? I don't think it's ever occurred to me to do that.
by ianamartin 9y ago
I'm piqued by one thing in this article. Using an object as a dictionary key. What's the use for that? I don't think it's ever occurred to me to do that.
- cakebrewery 9y agoAvoids the extra step of hashing the object to make the key by simply passing the object itself.
- talltimtom 9y agoAnything hashable can be a dict key, so if you have some mapping between one thing that’s hashable and other things, you can use a dict directly rather than having to come up with an index and keep track of that association.
- chubot 9y agoI'm not sure what part of the article you refer to, but: - If the objects are value types (as dataclasses are, since they respect equality): it makes sense to use them as dict keys, just as it makes sense to use tuples as dict keys. Changing a tuple to a namedtuple is natural. - If the objects have reference semantics rather than value semantics, you can still use them as dict keys in Python. The default __hash__ is the id/address of the object (the default __eq__ uses id() too). I don't particularly like this style but I have seen it used. It feels error-prone to me and not "algebraic".
- dagw 9y agoUsing an object as a dictionary key. What's the use for that? I've used tuples has dict keys several times, so I don't see why I conceivably wouldn't use a Data Class containing the same data as a dict key.
- comnetxr 9y agomemoization is a common use case. If you are doing an expensive computation that gives the same answer for the the same inputs, you can build a lookup table for cases you have already encountered to avoid recomputing. you can use an object to encapsulate the inputs (or the inputs might be objects already).
- UncleEntity 9y agoDynamic dispatching comes to mind. d = {Foo : do_something_with_foo, Bar : do_something_with_bar} d.get(type(x), default_function)(x) Probably some more efficient way but honestly I've used this before instead of writing a whole if elif chain. --edit-- Makes python's lack of a switch operator sometimes less painful...
- ianamartin 9y agoOh, that makes sense. Not sure why this question rubbed people the wrong way. I was genuinely curious about when you would use an object as a key. I guess my uses for dictionaries are pretty vanilla. But that’s a kind of thing I do all the time. I set up dictionaries where the key is a possible value from some operation or query, and the value is the function I want to perform on that value. This extends that concept. Thanks!