pythondictionarysortingnested

How to sort a nested dictionary (having a list) in python?


I am stuck with nested dictionary sorting. How to sort the following dictionary in the chronological order?

{2024: {
  'Jul': ['Rate', 'Hours', 'Cost']
  'Jan': ['Rate', 'Hours', 'Cost'],
  'Feb': ['Rate', 'Hours', 'Cost'],
  'Mar': ['Rate', 'Hours', 'Cost'],
  'Apr': ['Rate', 'Hours', 'Cost'],
  'May': ['Rate', 'Hours', 'Cost'],
  'Jun': ['Rate', 'Hours', 'Cost']}}

The output should be as below:

{2024: {
  'Jan': ['Rate', 'Hours', 'Cost'],
  'Feb': ['Rate', 'Hours', 'Cost'],
  'Mar': ['Rate', 'Hours', 'Cost'],
  'Apr': ['Rate', 'Hours', 'Cost'],
  'May': ['Rate', 'Hours', 'Cost'],
  'Jun': ['Rate', 'Hours', 'Cost'],
  'Jul': ['Rate', 'Hours', 'Cost']}}

Through internet search I could only find one level of nesting.


Solution

  • You could use an dictionary comprehension with an OrderedDict:

    #!/usr/bin/env python
    
    from collections import OrderedDict
    
    old = {2024: {
      'Jul': ['Rate', 'Hours', 'Cost'],
      'Jan': ['Rate', 'Hours', 'Cost'],
      'Feb': ['Rate', 'Hours', 'Cost'],
      'Mar': ['Rate', 'Hours', 'Cost'],
      'Apr': ['Rate', 'Hours', 'Cost'],
      'May': ['Rate', 'Hours', 'Cost'],
      'Jun': ['Rate', 'Hours', 'Cost']}}
    
    year = 2024
    ordered_months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']
    
    new = {year: OrderedDict({month: old[year][month] for month in ordered_months})}
    
    print(new)
    
    % ./so78881244.py
    {2024: OrderedDict([('Jan', ['Rate', 'Hours', 'Cost']), ('Feb', ['Rate', 'Hours', 'Cost']), ('Mar', ['Rate', 'Hours', 'Cost']), ('Apr', ['Rate', 'Hours', 'Cost']), ('May', ['Rate', 'Hours', 'Cost']), ('Jun', ['Rate', 'Hours', 'Cost']), ('Jul', ['Rate', 'Hours', 'Cost'])])}
    

    Perhaps keep in mind that objects/dictionaries are inherently unordered, until you manually apply an order on the keys you are reading from.