I am trying to get a sorted dictionary. But the order of the items between mydict
and orddict
doesn't seem to change.
from collections import OrderedDict
mydict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
orddict = OrderedDict(mydict)
print(mydict, orddict)
# print items in mydict:
print('mydict')
for k, v in mydict.items():
print(k, v)
print('ordereddict')
# print items in ordered dictionary
for k, v in orddict.items():
print(k, v)
# print the dictionary keys
# for key in mydict.keys():
# print(key)
# print the dictionary values
# for value in mydict.values():
# print(value)
Adding on to the answer by Brian,
OrderedDict
is really great. Here's why:You can use it as simple
dict
object because it supports equality testing with otherMapping
objects like collections.counter.OrderedDict
preserves the insertion order as explained by Brian. In addition to that it has a method popitem which returns (key,value) pairs in LIFO order. So, you can also use it as a mapped 'stack'.You not only get the full features of a
dict
but also, some cool tricks.So it only sorts by order of adding into the dict
You can build an OrderedDict order by key as follow,
orddict = OrderedDict(sorted(mydict.items(), key = lambda t: t[0]))
or simply as @ShadowRanger mentioned in comment
orddict = OrderedDict(sorted(d.items()))
If you want to order by value,
orddict = OrderedDict(sorted(mydict.items(), key = lambda t: t[1]))
More information in 8.3.5.1. OrderedDict Examples and Recipes
An
OrderedDict
preserves the order elements were inserted:So an
OrderedDict
does not order the elements for you, it preserves the order you give it.If you want to "sort" a dictionary, you probably want
From the documentation for
OrderedDict
(emphasis mine):As of Python 3.7, a new improvement is:
This means there is no real need for
OrderedDict
anymore