Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I call iteritems() on a Python dict, how is the order of the resulting list determined? [duplicate]

I know Python dicts are unordered, but if you call iteritems(), it returns a list, which is ordered. How is the ordering of that list determined?

like image 357
mdornfe1 Avatar asked Jan 21 '26 23:01

mdornfe1


1 Answers

The order is determined by the order they appear in the dict's internal table. Which is essentially the hash of the object mod the length of that table (plus some offset when there are hash collisions). The order will change anytime the size of the internal table changes, which can happen anytime you add an item (or less often when you remove items) from the dict.

You cannot reasonably predict it, and shouldn't rely on dictionary ordering for any purpose.

Read this:

Python dictionary implementation

like image 153
joshua Avatar answered Jan 24 '26 19:01

joshua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!