Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the order of dict and dict.items() different?

>>> d = {'A':1, 'b':2, 'c':3, 'D':4}

>>> d
{'A': 1, 'D': 4, 'b': 2, 'c': 3}

>>> d.items()
[('A', 1), ('c', 3), ('b', 2), ('D', 4)]

Does the order get randomized twice when I call d.items()? Or does it just get randomized differently? Is there any alternate way to make d.items() return the same order as d?

Edit: Seems to be an IPython thing where it auto sorts the dict. Normally dict and dict.items() should be in the same order.

like image 318
Kevin Avatar asked Jan 06 '23 10:01

Kevin


1 Answers

You seem to have tested this on IPython. IPython uses its own specialized pretty-printing facilities for various types, and the pretty-printer for dicts sorts the keys before printing (if possible). The d.items() call doesn't sort the keys, so the output is different.

In an ordinary Python session, the order of the items in the dict's repr would match the order of the items from the items method. Dict iteration order is supposed to be stable as long as a dict isn't modified. (This guarantee is not explicitly extended to the dict's repr, but it would be surprising if the implicit iteration in repr broke consistency with other forms of dict iteration.)

like image 136
user2357112 supports Monica Avatar answered Jan 13 '23 09:01

user2357112 supports Monica