[PYTHON] collections.OrderedDict

OrderedDict I remember the order

import collections

d = {'apple': 4, 'banana': 3, 'pear': 1, 'orange': 2}

#Sort in alphabetical order, t if you want to sort in value order[1]To
od = collections.OrderedDict(sorted(d.items(), key=lambda t: t[0]))
print(od)

#Will be added at the end
od['cc'] = 100
print(od)

Execution result:

OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1), ('cc', 100)])

Recommended Posts

collections.OrderedDict