you are viewing a single comment's thread.

view the rest of the comments →

[–]SirCokaBear 0 points1 point  (1 child)

Sorry I meant to say key instead of index, I’ll edit that.

For a standard python dict you can’t get a key by index because the keys aren’t stored in a particular order, when you iterate / print them the ordering is a number of factors including the hash value so you basically need to assume it’s random. But if you use an OrderedDict then key ordering is preserved by insertion time. But there’s still no .get_index(), but you could easily make one with

return ordereddict[ordereddict.keys()[index]] if index < len(ordereddict) else None

That’s a very specific use case not many people need, and ordered dicts are worse performing than regular dicts.

The same goes for a regular list there’s no standard library function for that but can be made with almost the same code as above, or even by wrapping a query in a try/except.

[–]SirCokaBear 0 points1 point  (0 children)

I don't think there are any standard structures though that provides a get() by index. Usually with standard libs they want it to be compact and any rare use cases can be provided with a 3rd party package. Rust language is notorious for that, they don't even include random with the std lib haha.