Home > Mobile >  How do I get the last inserted key in Python (>3.7) dict without iterating through the whole list
How do I get the last inserted key in Python (>3.7) dict without iterating through the whole list

Time:12-12

I know that Python dict's keys() since 3.7 are ordered by insertion order. I also know that I can get the first inserted key in O(1) time by doing next(dict.keys())

What I want to know is, is it possible to get the last inserted key in O(1)? Currently, the only way I know of is to do list(dict.keys())[-1] but this takes O(n) time and space.

By last inserted key, I mean:

d = {}
d['a'] = ...
d['b'] = ...
d['a'] = ...
The last inserted key is 'b' as it's the last element in d.keys()

CodePudding user response:

Dicts support reverse iteration:

next(reversed(d))

CodePudding user response:

@[user2357112 supports Monica]'s next(reversed(d)) does the trick. I'll add that, when I want the most recently added key, I usually want to remove it from the dict too. In that case, a simple d.popitem() does the trick.

  • Related