From the discussion here I understand that dictionaries in general are not ordered, at least not in a reliable fashion. So why do the dictionary methods keys(), values(), items() return ordered lists instead of e.g. unordered sets? Is it just a matter of convenience or is there some underlying reasoning?
-
6First, `values` are *not* guaranteed unique.. – user2864740 Aug 10 '18 at 16:27
-
Dictionary keys and values (if iterated over separately) are always in the same order. Using sets for either would make this impossible. – kindall Aug 10 '18 at 16:29
2 Answers
They don't return lists or sets; they return views. Key views are set-like, and item views are set-like as long as the values are hashable, but value views cannot be set-like, as there can be duplicate values.
Before Python 3, they returned lists, but those methods predated the introduction of sets. Sets were introduced in Python 2.4, while keys
/values
/items
have been around since at least 1.4, and probably before 1.0.

- 260,549
- 28
- 431
- 505
Based on the Python docs, the sets
module wasn't introduced until Python 2.3, well after the dictionary type was established. It would have been a breaking change to redefine how keys()
, values()
etc worked.
In Python 3, those functions return view objects rather than lists which, while iterable, don't suggest an explicit ordering in the way that an ordered list does.

- 76
- 1
- 4