83978

python sort OrderedDict keys chronologically

Question:

I have the following OrderedDict:

from collections import OrderedDict a = OrderedDict() a['2016:April'] = 1 a['2016:January'] = 2 a['2017:February'] = 3 a['2015:November'] = 4

I would like to sort the dictionary by the keys in chronological order so that the result is:

OrderedDict([('2015:November', 4), ('2016:January', 2), ('2016:April', 1), ('2017:February', 3)])

Answer1:

You need to recreate the OrderedDict by passing sorted items; (OrderedDict remembers key insertion order)

import calendar from collections import OrderedDict months = {calendar.month_name[i]: i for i in range(1, 13)} # => {'January': 1, 'February': 2, .... 'December': 12} def get_month_from_key(item): # Convert '2015:November' to (2015, 11) # Return value of this function is used to compare dictionary keys. year, month = item[0].split(':') # item[0] is key return int(year), months.get(month, -1) a = OrderedDict() a['2016:April'] = 1 a['2016:January'] = 2 a['2017:February'] = 3 a['2015:November'] = 4 a = OrderedDict(sorted(a.items(), key=get_month_from_key)) # => OrderedDict([('2015:November', 4), ('2016:January', 2), # ('2016:April', 1), ('2017:February', 3)])

Recommend

  • Can't understand why is prolog looping infinitly
  • Reverse a csv file
  • Concatenate multiple histograms in matplotlib
  • Draw text vertically on canvas
  • Asp.Net - Detect no javascript on page? (renamed title)
  • Getting R to store the working directory for every session
  • Store time between records
  • How do I get back to the beginning in kcachegrind?
  • Error: “You have been creating or deleting too many calendars or calendar events in a short time.”
  • Is it possible to restore a GraphicsDevice if something goes wrong with it?
  • Why the time complexity of an array insertion is O(n) and not O(n+1)? [duplicate]
  • Optimizing Memory in Android when managing Fragment Transactions
  • Find 4 minimal values in 4 __m256d registers
  • Dynamic SQL with variables inside a view (SQL Server)
  • pure javascript dom dynamic insert, update and delete
  • Python find continuous interesctions of intervals
  • How do I check if System::Collections:ArrayList is empty / nullptr / null?
  • Creating a C++ function that calls other Lua function
  • How to turn (A, B, C) into (AB, AC, BC) with Pig?
  • Cypher - matching two different possible paths and return both
  • How to use function wrapper in mustache.php?
  • ListItem.Attributes.Add not working
  • Sort List of Strings By Version
  • How to suppress a dialog
  • Breeze - Deleted Items nav properties bug
  • Why value captured by reference in lambda is broken? [duplicate]
  • javaw.exe and eclipse startup problems
  • Statically linking a C++ library to a C# process using CLI or any other way
  • php design question - will a Helper help here?
  • AngularJs get employee from factory
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Why joiner is not used after Sequence generator or Update statergy
  • need help with bizarre java.net.HttpURLConnection behavior
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • Recursive/Hierarchical Query Using Postgres
  • How can i traverse a binary tree from right to left in java?
  • UserPrincipal.Current returns apppool on IIS
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How do I use LINQ to get all the Items that have a particular SubItem?