0

I have a dictionary that looks like this:

{
  "dates":
    {
      "2020-01-01": "something 1",
      "2019-04-20": "something 2",
      "2020-03-15": "something 3",
      "2019-12-31": "something 4"
    }
}

Let's assume this dictionary is stored under a variable name my_dictionary.

How do I sort my_dictionary["dates"] by date (preferrably by a datetime format which I can define by myself)?

Thank you

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
neisor
  • 384
  • 4
  • 15
  • 1
    Is there a particular reason you want to sort your dictionary? Generally in most languages dicts / hashes are unordered. – Chris Doyle Jul 30 '21 at 12:29
  • Yes, there is a reason. I am looping through this kind of dict and I am checking for differences between the dates' values in a loop - for this to work correctly, I need the dictionary to be sorted by date correctly. – neisor Jul 30 '21 at 12:33
  • 2
    `my_dictionary["dates"] = dict(sorted(my_dictionary["dates"].items()))`? or just iterate directly over `sorted(my_dictionary["dates"].items())`. – Axe319 Jul 30 '21 at 12:35
  • Previous questions/answers do mostly use Python2 (not Python3) and do not sort by dates, but they rather sort by numbers (e.g. 1, 2, 3...) or by characters (e.g. 'a', 'b', 'c'...). – neisor Jul 30 '21 at 12:36
  • 1
    @Axe319 - thank you! Your solution seemed to work out! – neisor Jul 30 '21 at 12:40

2 Answers2

0

To sort by dates, you could convert each of the strings to datetime objects and sort that way:

from datetime import datetime

dates = {
    "2020-01-01": "something 1",
    "2019-04-20": "something 2",
    "2020-03-15": "something 3",
    "2019-12-31": "something 4",
}

dates = dict(
    sorted(dates.items(), key=lambda item: datetime(*map(int, item[0].split("-"))))
)

However, with the way that your dates are formatted, you can just sort normally without issues, hence @Axe319's solution in the comments works perfectly:

dates = {
        "2020-01-01": "something 1",
        "2019-04-20": "something 2",
        "2020-03-15": "something 3",
        "2019-12-31": "something 4",
    }

dates = dict(sorted(dates.items()))
Rolv Apneseth
  • 2,078
  • 2
  • 7
  • 19
0

you can use this code:

d={

"dates":
    {
      "2020-01-01": "something 1",
      "2019-04-20": "something 2",
      "2020-03-15": "something 3",
      "2019-12-31": "something 4"
    }
}

for w in sorted(d, key=d.get, reverse=False):
    print(d[w])
inv_map = {v: k for k, v in d[w].items()}
print(inv_map)
for w in sorted(inv_map, key=inv_map.get, reverse=True):
    print(inv_map[w])

Output:

{'2020-01-01': 'something 1', '2019-04-20': 'something 2', '2020-03-15': 'something 3', '2019-12-31': 'something 4'}
{'something 1': '2020-01-01', 'something 2': '2019-04-20', 'something 3': '2020-03-15', 'something 4': '2019-12-31'}
2020-03-15
2020-01-01
2019-12-31
2019-04-20
Salio
  • 1,058
  • 10
  • 21