如果词典是序列的对象,则如何通过其值对其进行排序?
我有一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用
dictionary.items()
获取键对值而不是仅值dictionary.values()
x [0]
是键和x [1]
是值(timeDelta),您可以简单地删除.days
,因为它具有内置的比较,但是当出现复杂对象时,您必须指定哪个属性是排序的密钥Simply using
dictionary.items()
to get key-pair value instead of only valuesdictionary.values()
x[0]
is key andx[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