0

I am trying to display a dictionary according to the latest date time entry. my date time is in a tuple that is stored to a key and its the first value in the tuple. *** this dictionary reads content from a text file so my dictionary = {}

{'xavier': ('2020-08-13 13:34:01', 'running'), 'alvin': ('2020-08-14 14:34:10', 'basketball')}

anyone knows how to display it such that the key and values under 'alvin' displays first since the date time entry is the latest. something like this:

alvin ('2020-08-14 14:34:10', 'basketball')
xavier ('2020-08-13 14:34:01', 'running')

Thanks much!!

ellie
  • 15
  • 2

4 Answers4

2

You may use

from datetime import datetime

dct = {'xavier': ('2020-08-13 13:34:01', 'running'), 'alvin': ('2020-08-14 14:34:10', 'basketball')}


def sorter(item):
    """ Returns a datetime object """
    return datetime.strptime(item[1][0], '%Y-%m-%d %H:%M:%S')

print(sorted(dct.items(), key=sorter, reverse=True))
Jan
  • 42,290
  • 8
  • 54
  • 79
  • hi Jan! sorry i did not add this in but my dictionary actually reads content from a text file. so my dict = {} do you know how to go about doing it? :) – ellie Aug 14 '20 at 09:29
1

What you can do is, to work on a list-like structure, which you get from dict.items() and sort it with the help of the sorted() function.

An example:

d = {
    'xavier': ('2020-08-13 13:34:01', 'running'), 
    'alvin': ('2020-08-14 14:34:10', 'basketball'),
    'peter': ('2020-08-19 16:42:00', 'tennis')
}

sd = sorted(d.items(), key=lambda x: x[1][0], reverse=True)

for item in sd:
    print(item)
# ('peter', ('2020-08-19 16:42:00', 'tennis'))
# ('alvin', ('2020-08-14 14:34:10', 'basketball'))
# ('xavier', ('2020-08-13 13:34:01', 'running'))

Explanations:

  • The key argument is used to retrieve an object to run the comparison on, i.e. the example will work on the date string
  • The sorting works even though you provide only string, as it is in the right format, it might not work correctly if you work on another form, e.g. 14.08.2020. You can use the datetime library then.
AnsFourtyTwo
  • 2,480
  • 2
  • 13
  • 33
  • 1
    As of `Python 3.5 (6?)` they actually do have an order. – Jan Aug 14 '20 at 09:19
  • See https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 It was 3.6 – Jan Aug 14 '20 at 09:20
  • 1
    OK, but they are not ordered by any criteria based on it's content. They are ordered based on the insertions made. Thanks anyway. Good to know. – AnsFourtyTwo Aug 14 '20 at 09:24
  • 1
    Well, if you use a comprehension based on some criteria then that's how the get inserted. Meaning: `dct = {key: value for key, value in sorted(dct.items(), key=lambda x: x[1])}` will actually follow a rule. – Jan Aug 14 '20 at 09:26
  • thanks for your input! sorry i did not add this in but my dictionary actually reads content from a text file. so my dict = { } do you know how to go about doing it? :) – ellie Aug 14 '20 at 09:31
  • That's another question, but possibly you read it with the `json` library. See @shreyaskars answer. – AnsFourtyTwo Aug 14 '20 at 09:53
0

sorted would be a choice.

from datetime import datetime

your_dict = {'xavier': ('2020-08-13 13:34:01', 'running'), 'alvin': ('2020-08-14 14:34:10', 'basketball')}
for k, v in sorted(your_dict.items(), key=lambda item: datetime.strptime(item[1][0], "%Y-%m-%d %H:%M:%S"), reverse=True):
    print(k, v)

mustafasencer
  • 723
  • 4
  • 12
0

You may find this useful

import json

file_data = ''
filepath = 'filepath' #your filepath
with open(filepath, 'r', encoding='utf-8') as f:
    file_data = f.read()
my_dictionary = json.loads(file_data) #string file data converted to dictionary in Python

new_sorted_data = sorted(my_dictionary.items(), key=lambda x:x[1][0], reverse=True)
for i in new_sorted_data:
    print(i[0], i[1])

shreyaskar
  • 375
  • 1
  • 3
  • 14