-1

How do I find the key for the latest date value of a dictionary where the dates are represented as strings?

I tried using max(date, key=date.get) as in Getting key with maximum value in dictionary?, but it returns wrong results:

date = {"sale_date": "2018-02-17 20:11:37.017298",
        "buy_date": "2018-02-2 20:11:37.017298"}

latest = max(date, key=date.get) 

This returns "buy_date" but clearly the result should be "sale_date".

Georgy
  • 12,464
  • 7
  • 65
  • 73

2 Answers2

1

You can use something like this:

> date={"sale_date":"2018-02-17 20:11:37.017298","buy_date":"2018-02-1 20:11:37.017298"}
> sorted([(value,key) for key,value in date.items()], key=lambda x:x[1])[0][1]
'sale_date'

by adding reversed=True to the sorted function, you can have it reversed.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

If your values are in str format you can change it to date format, date is comparable So you can take the max to get latest date, Also for finding key with value in python you can try the below method:

dt={"sale_date":"2018-02-17 20:11:37.017298",
      "buy_date":"2018-02-1 20:11:37.017298" }
l = [datetime.datetime.strptime(j, "%Y-%m-%d %H:%M:%S.%f") for j in dt.values()]
for k,v in dt.items():
    if v == str(max(l)):
        print(k)

Avoid giving variables name like date, string... etc

Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33