如果词典是序列的对象,则如何通过其值对其进行排序?

发布于 2025-01-26 06:08:10 字数 378 浏览 1 评论 0原文

我有一个python词典,其中键是字符串形式的用户名,并且值以timeDelta对象的形式。我需要按顺序从最小到最小的顺序排序值,然后访问键,以便我可以在文件中使用其用户名打印出十大值。

一旦我使用排序(dictionary.values())对值进行排序,我该如何访问用户名?我已经尝试了字典[dateTime.timedelta(seconsts = 84081)],但我得到一个属性错误:dateTime.dateTime.dateTime'没有属性'TIMEDELTALTA。 (仅供参考,我使用了:来自DateTime Import DateTime,TimeDelta。)。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

段念尘 2025-02-02 06:08:10

只需使用dictionary.items()获取键对值而不是仅值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]是键和x [1]是值(timeDelta),您可以简单地删除.days,因为它具有内置的比较,但是当出现复杂对象时,您必须指定哪个属性是排序的密钥

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文