3

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?

2 Answers2

10

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

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.

Paul Hendry
  • 76
  • 1
  • 4