We know in Python 3.6 dictionaries are insertion ordered as an implementation detail, and in 3.7 insertion ordering can be relied upon.
I expected this to also be the case for subclasses of dict
such as collections.Counter
and collections.defaultdict
. But this appears to only hold true for the defaultdict
case.
So my questions are:
- Is it true that ordering is maintained for
defaultdict
but not forCounter
? And, if so, is there a straightforward explanation? - Should ordering of these
dict
subclasses in thecollections
module be considered implementation details? Or, for example, can we rely ondefaultdict
being insertion ordered likedict
in Python 3.7+?
Here are my rudimentary tests:
dict: ordered
words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"]
dict_counter = {}
for w in words:
dict_counter[w] = dict_counter.get(w, 0)+1
print(dict_counter)
# {'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2}
Counter: unordered
from collections import Counter, defaultdict
print(Counter(words))
# Counter({'apples': 3, 'kiwis': 2, 'oranges': 1, 'bananas': 1})
defaultdict: ordered
dict_dd = defaultdict(int)
for w in words:
dict_dd[w] += 1
print(dict_dd)
# defaultdict(<class 'int'>, {'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2})