-1

Sorting a dictionary whose value is in the form of list of dictionary.

I have something like:

myDict = {'First' :[{'Name':'Raj','Date':'28-March-2019 09:30'}], 
          'Second':[{'Name':'Ajay','Date':'12-April-2020 07:25'}], 
          'Third':[{'Name':'Jaya','Date':'12-April-2019 09:25'}]}

I want to sort this in ascending order based on Date.

Expected output:

myDict = {'First' :[{'Name':'Raj','Date':'28-March-2019 09:30'}], 
          'Third' :[{'Name':'Jaya','Date':'12-April-2019 09:25'}],
          'Second':[{'Name':'Ajay','Date':'12-April-2020 07:25'}]}

I want the output in the form of dictionary

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Us86
  • 13
  • 1
  • 1
    you can use collections.OrderedDict, or do you want a list with all the values sorted? – kederrac Mar 19 '20 at 09:01
  • I want the output in the form of dictionary only – Us86 Mar 19 '20 at 09:03
  • Can you the exact expected output ? – azro Mar 19 '20 at 09:03
  • What did you try to sort and output it? [mre]? What went wrong? Your dates are text, not datetimes- and as for the date format:it is not possible to sort it just by string comparison.How do you transform it so it is comparable? Why are your values list of dictionaries if they all only have 1 dict inside - could there be more then 1 inside? If more then 1 inside, which date to use to sort by? – Patrick Artner Mar 19 '20 at 09:04
  • Does each value list only have one dictionary or can it have multiple (i.e. you only show single dictionaries in list)? – DarrylG Mar 19 '20 at 09:36

1 Answers1

1

you can use collections.OrderedDict with the build-in function sorted:

from collections import OrderedDict
from datetime import datetime

OrderedDict(sorted(myDict.items(), key=lambda x: datetime.strptime(x[1][0]['Date'], '%d-%B-%Y %H:%M')))

this solution assumes that each value from myDict is a list with one dict inside which has a valid 'Date' key (as your provided data shows)

in python2.7 dictionary insertion order it is not guaranteed, so you can't get your desired output, still, you can use OrderedDict

output:

OrderedDict([('First', [{'Name': 'Raj', 'Date': '28-March-2019 09:30'}]),
             ('Third', [{'Name': 'Jaya', 'Date': '12-April-2019 09:25'}]),
             ('Second', [{'Name': 'Ajay', 'Date': '12-April-2020 07:25'}])])

you can read more about OrderedDict here

I encourage you to use python3.6 or a higher version where you can benefit from the insertion order in a dict

kederrac
  • 16,819
  • 6
  • 32
  • 55