Sort by date in python

Status

I want to sort because the value is entered by date for the key in the python dictionary.

What I tried

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))

How to sort dictionaries by date?

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

  1. Convert the dictionary once to a two-dimensional array of keys and values
  2. Sort in the state of a two-dimensional array
  3. Return to dictionary

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

Code actually written

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

Sort by date in python
Bubble sort in Python
Get date in Python
Custom sort in Python3
Date calculation in Python
Naturally sort Path in Python
python in mongodb in descending sort
String date manipulation in Python
Sort by file modification date
[Python] Sort
Python # sort
Sort large text files in Python
Sort by specifying conditions in CASTable
When specifying multiple keys in python sort
Python in optimization
CURL in python
New in Python 3.9 (2)-Sort directed acyclic graphs in Python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Python date arithmetic
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
Function to save images by date [python3]
N-Gram in Python
Programming in python
Read the file line by line in Python
Automate jobs by manipulating files in Python
Plink in Python
Sort the file names obtained by Python glob in numerical order
Constant in python
Lifegame in Python.
FizzBuzz in Python
StepAIC in Python
N-gram in python
Csv in python
Disassemble in Python
Reflection in Python
Sort by pandas
Implemented Stooge sort in Python3 (Bubble sort & Quicksort)
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Alignment algorithm by insertion method in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
Scene recognition by GIST features in Python