Home > other >  Why I can't get dictionary keys by index?
Why I can't get dictionary keys by index?

Time:03-27

Since Python 3.7, dictionaries are ordered. So why I can't get keys by index?

CodePudding user response:

Building in such an API would be an "attractive nuisance": the implementation can't support it efficiently, so better not to tempt people into using an inappropriate data structure.

It's for much the same reason that, e.g., a linked list rarely offers an indexing API. That's totally ordered too, but there's no efficient way to find the i'th element for an arbitrary i. You have to start at the beginning, and follow i links in turn to find the i'th.

Same end result for a CPython dict. It doesn't use a linked list, but same thing in the end: it uses a flat vector under the covers, but basically any number of the vector's entries can be "holes". There's no way to jump over holes short of looking at each entry, one at a time. People expect a[i] to take O(1) (constant) time, not O(i) time.

CodePudding user response:

Here's a workaround if you're really desperate for this functionality:

In [2]: d
Out[2]: {'a': 'A', 'b': 'B', 'c': 'C'}

In [3]: indexed_keys = dict(enumerate(d.keys()))

In [4]: d[indexed_keys[1]]
Out[4]: 'B'

So keys is a dictionary itself, but whose key values directly correspond to the "index" at which the keys of d are located. So getting the key at index i is still O(1). Now you're using two O(1) look ups to get a value associated with a key's "index" in the original dictionary.

This obviously wouldn't work if your original dictionary's keys collide with their enumeration, but if that happens you have bigger issues to work out -- like picking a more appropriate data structure.

  • Related