Difference between dictionary and OrderedDict

2020-02-25 08:16发布

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)

5条回答
Deceive 欺骗
2楼-- · 2020-02-25 08:57

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 other Mapping 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.

查看更多
做个烂人
3楼-- · 2020-02-25 09:03

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

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

查看更多
4楼-- · 2020-02-25 09:08

An OrderedDict preserves the order elements were inserted:

>>> od = OrderedDict()
>>> od['c'] = 1
>>> od['b'] = 2
>>> od['a'] = 3
>>> od.items()
[('c', 1), ('b', 2), ('a', 3)]
>>> d = {}
>>> d['c'] = 1
>>> d['b'] = 2
>>> d['a'] = 3
>>> d.items()
[('a', 3), ('c', 1), ('b', 2)]

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

>>> sorted(d.items())
[('a', 1), ('b', 2), ('c', 3)]
查看更多
成全新的幸福
5楼-- · 2020-02-25 09:14

From the documentation for OrderedDict (emphasis mine):

Some differences from dict still remain:

  • The regular dict was designed to be very good at mapping operations. Tracking insertion order was secondary.

  • The OrderedDict was designed to be good at reordering operations. Space efficiency, iteration speed, and the performance of update operations were secondary.

  • Algorithmically, OrderedDict can handle frequent reordering operations better than dict. This makes it suitable for tracking recent accesses (for example in an LRU cache).

  • The equality operation for OrderedDict checks for matching order.

  • The popitem method of OrderedDict has a different signature. It accepts an optional argument to specify which item is popped.

  • OrderedDict has a move_to_end method to efficiently reposition an element to an endpoint.

  • Until Python 3.8, dict lacked a __reversed__ method.

查看更多
老娘就宠你
6楼-- · 2020-02-25 09:19

As of Python 3.7, a new improvement is:

the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.

This means there is no real need for OrderedDict anymore

查看更多
登录 后发表回答