I want to sort because the value is entered by date for the key in the python dictionary.
In the first place, a dictionary has keys and values, which is complicated, so first think about it in a list. I tried it.
list = [2020-1-2,2019-3-4,2020-2-4]
print(sorted(list))
result
[2012, 2014, 2017]
What's this
I did it here and it worked.
list = ['2020-1-2','2019-3-4','2020-2-4']
print(sorted(list))
Then it is the main subject.
There are many ways to sort the list by date, but there weren't many dictionaries, so I thought about how to do it this time.
As a method
If this is the case, you can use the sorting method that came out after checking.
I referred to the following article for how to sort by date in 2D array. https://cre8cre8.com/python/sort_string_date.htm
dict = {'panf1':'2020-2-1','panf2':'2019-3-4','panf4':'2020-1-3'}
list1 = []
sorted_dict={}
print(dict)
for i,j in dict.items():
list2=[]
list2.append(i)
list2.append(j)
list1.append(list2)
print(list1)
sorted_data = sorted(list1,key=lambda x:x[1],reverse=True)
print(sorted_data)
for k in sorted_data:
sorted_dict[k[0]]=k[1]
print(sorted_dict)
Recommended Posts