Python OrderdDict values() function saves the order?

200 views Asked by At

Does orderedDict.values(), .keys(), .iterkeys() etc. returns the values in the order that items were first inserted?

I assume that values\keys function does not change the order of the dict, and if it's orderedDict, then i get the values in the order that they were added to the dictionary.

That's true?

2

There are 2 answers

0
uranusjr On

Your assumption is correct. OrderedDict maintains a list of (thus ordered) keys to iterate over values and keys, so they will always be ordered the same way as in for loops.

The comments in the source code also states this, saying:

The inherited dict provides __getitem__, __len__, __contains__, and get. The remaining methods are order-aware. Big-O running times for all methods are the same as regular dictionaries.

Emphasis mine.

0
UltraInstinct On

Does orderedDict.values(), .keys(), .iterkeys() etc. returns the values in the order that items were first inserted?

Yes, they are preserved. From the documentation (emphasis mine):

Equality tests between OrderedDict objects are order-sensitive and are implemented as list(od1.items())==list(od2.items()).

Thats how equality comparison is done, and it implies that the result of items() are ordered. Now for other two functions you can look into a substitute implementation for OrderedDict here