cpython icon indicating copy to clipboard operation
cpython copied to clipboard

Add `dict` move_to_end(last=False) functionality in the `OrderedDict` documentation

Open Drblessing opened this issue 1 year ago • 1 comments

Documentation

In the OrderedDict Objects documentation it states:

"A regular dict does not have an efficient equivalent for OrderedDict’s od.move_to_end(k, last=False) which moves the key and its associated value to the leftmost (first) position."

This can easily be accomplished in two ways:

value = d.pop(key)
d = {key: value, **d}
value = d.pop(key)  # Remove the key-value pair from the dictionary
new_dict = {key: value}  # Create a new dictionary with the key-value pair
new_dict.update(d)  # Add the rest of the original dictionary

Drblessing avatar Jul 15 '24 01:07 Drblessing

I'm not sure those qualify as "efficient".

ericvsmith avatar Jul 15 '24 01:07 ericvsmith

I'm not sure those qualify as "efficient".

You're right. Definitely not space, maybe they're not too inefficient time wise?

Drblessing avatar Jul 15 '24 02:07 Drblessing

I'm not sure those qualify as "efficient".

You're right. Definitely not space, maybe they're not too inefficient time wise?

The proposed workaround requires O(n) complexity in both space and time, while with an OrderedDict only O(1) is required in both space and time.

blhsing avatar Jul 15 '24 02:07 blhsing

The proposed workaround requires O(n) complexity in both space and time, while with an OrderedDict only O(1) is required in both space and time.

Thank you for the correction.

Drblessing avatar Jul 15 '24 02:07 Drblessing