Saqib Ali
Saqib Ali

Reputation: 12565

Does python's dict.items() always return the same order?

Is it guaranteed that python 2.X's built-in methods dict.items() and dict.iteritems() will always return items in the same order? Or are these methods non-deterministic?

Upvotes: 4

Views: 2085

Answers (3)

Shay Maor
Shay Maor

Reputation: 17

If you're interested, you are able to use Visual Code and add breakpoints at each point that you're interested and monitor the local variables for differences across code runs... whether through the same program flow or through a separate run. You are also able to add expression watches. This will allow you to confirm for yourself the behavior of dictionary methods including the dict.items() and dict.iteritems()

Upvotes: 0

Tim Peters
Tim Peters

Reputation: 70592

Within a single run of a program, and provided a dict d is not mutated in between, then

d.items()
d.iteritems()
d.keys()
d.iterkeys()
d.values()
d.itervalues()

are all consistent with each, and each returns the same sequence each time.

But if you modify the dict, it may shrink or grow and rearrange itself internally, which can change the order. Which will then remain the same until the next mutation.

EDIT: one exception, which is quite deliberate. If you merely replace the value associated with an existing key, the order will not change. So if k in d is True, d[k] = v is harmless. All bets are off if you add a new key, or delete a key, though.

Upvotes: 6

wailinux
wailinux

Reputation: 139

you need customize function like that:

d = {'a': 4, 'c': 1, 'b': 2, 'd': 3}
def sorteddict(d={}):
    return sorted(d.items(),key=lambda x: x[1])
print(sorteddict(d))

Upvotes: -1

Related Questions