I'm trying to sort a nest dictionary by key which is a string date and I'm using the strptime
function on the key argument of the sorted function but I keep getting key errors?
dict1 = {1: {'Oct-2021': 175967.7, 'Nov-2021': 132086.3, 'Sep-2021': 158312.7, 'Aug-2021': 244930.3,
'Dec-2021': 114293.8, 'Jan-2022': 117409.2, 'Feb-2022': 55355.1}}
dict2 = dict(sorted(dict1, key=lambda x: datetime.strptime(x[1][0], "%b-%Y"), reverse=True))
CodePudding user response:
You're trying to sort the outer dictionary by the keys in the nested dict, which doesn't make sense. It seems you're trying to sort the inner dicts by the keys, so you could use a dict comprehension where in each iteration, you pass the keys in the key-value pairs of the inner dictionary to datetime.strptime
as a sorting key to sort them:
out = {k: dict(sorted(v.items(), key=lambda x: datetime.strptime(x[0], "%b-%Y"),
reverse=True)) for k,v in dict1.items()}
Output:
{1: {'Feb-2022': 55355.1,
'Jan-2022': 117409.2,
'Dec-2021': 114293.8,
'Nov-2021': 132086.3,
'Oct-2021': 175967.7,
'Sep-2021': 158312.7,
'Aug-2021': 244930.3}}