jab
jab

Reputation: 5823

Any Drawback to Using Tuples as Dictionary Keys in Python?

Seems like there should be...

Right now it just seems like magic that you can hash multidimensionally to the same table, without any negative effects.

Upvotes: 1

Views: 1644

Answers (2)

msw
msw

Reputation: 43527

From the dictionary's perspective, there's not a single thing multi-dimensional about it. The dictionary has no idea that you are interpreting the keys as describing an n-space.

You could, for example, cleverly pack your vector into a string which would seem less magical, be more complicated to get right, and yet be functionally equivalent. Python strings are Yet Another Immutable Sequence as far as the interpreter is concerned.

There is no negative effect.

Some tasks might be less efficient than an alternate implementation. For example if you are using (x, y, z) coordinates as keys, finding all points at some z will be time consuming relative to a real multi-dimensional store. But sometimes clarity and ease of implementation and reading trump efficient store.

Upvotes: 4

Nathan Binkert
Nathan Binkert

Reputation: 9134

The only drawback is performance. Larger keys mean longer times to hash.

Simply put, the only requirement of keys in a python dict is that they be immutable and hashable. For tuples (which are immutable), this means that you just need to combine the hashes of the sub-objects (which themselves must be immutable and hashable). You can also use a frozenset as a key. You can't use lists or dicts or sets as keys.

Upvotes: 2

Related Questions