0

I have a python dictionary in which the keys are usernames in the form of strings and the values are in the form of timedelta objects. I need to sort the values in order from greatest to least and then access the keys so I can print the top ten values with their usernames in a file.

Once I sort the values using sorted(dictionary.values()), how do I access the usernames? I already tried dictionary[datetime.timedelta(seconds=84081)] but I get an attribute error: datetime.datetime’ has no attribute ‘timedelta. (FYI, I used: from datetime import datetime, timedelta.)

FObersteiner
  • 22,500
  • 8
  • 42
  • 72

1 Answers1

0

Simply using dictionary.items() to get key-pair value instead of only values dictionary.values()

from datetime import datetime, timedelta

dct = {
    'User1': timedelta(days = 12),
    'User2': timedelta(days = 232),
    'User3': timedelta(days = 152),
    'User4': timedelta(days = 323),
    'User5': timedelta(days = 172),
    'User6': timedelta(days = 312),
    'User7': timedelta(days = 512),
    'User8': timedelta(days = 192),
    'User9': timedelta(days = 612),
    'User10': timedelta(days = 172),
    'User11': timedelta(days = 912),
}

print(sorted(dct.items(), key= lambda x: x[1].days))

x[0] is key and x[1] is value (timedelta), you can simply remove .days because it has built-in comparison, but when coming up complex object, you have to specify which attribute is sorted key

Tấn Nguyên
  • 1,607
  • 4
  • 15
  • 25