我的代码是:
a = {"key1": 5 , "key2": "8 hours ago", "key3": 2}
b = {"key1": 7 , "key2": "42 hours ago", "key3": 9}
c = {"key1": 6 , "key2": "1 hour ago", "key3": 1}
undecorated = [a, b, c]
undecorated.sort(key=operator.itemgetter('key2'))
结果是:
[
{"key1": 6 , "key2": "1 hour ago", "key3": 1}
{"key1": 7 , "key2": "42 hours ago", "key3": 9}
{"key1": 5 , "key2": "8 hours ago", "key3": 2}
]
但结果需要:
[
{"key1": 6 , "key2": "1 hour ago", "key3": 1}
{"key1": 5 , "key2": "8 hours ago", "key3": 2}
{"key1": 7 , "key2": "42 hours ago", "key3": 9}
]
答案 0 :(得分:8)
如果key2
的值与此处显示的一样正常,您可以执行以下操作:
undecorated.sort(key=lambda d: int(d['key2'].split()[0]))
答案 1 :(得分:3)
正如评论中已经解释的那样,由于您的比较键是字符串,因此它们按字典顺序进行比较。您可以使用dateparser
模块(pip install dateparser
)将字符串解析为datetime
正确比较的对象:
>>> from dateparser import parse
>>> undecorated.sort(key=lambda x: parse(x["key2"]), reverse=True)
>>> undecorated
[{'key1': 6, 'key2': '1 hour ago', 'key3': 1}, {'key1': 5, 'key2': '8 hours ago', 'key3': 2}, {'key1': 7, 'key2': '42 hours ago', 'key3': 9}]
答案 2 :(得分:0)
由于比较键有点复杂,我更喜欢将它设为函数而不是lambda,它可以包含try-except,并且更具可读性:
a = {"key1": 5, "key2": "8 hours ago", "key3": 2}
b = {"key1": 7, "key2": "42 hours ago", "key3": 9}
c = {"key1": 6, "key2": "1 hour ago", "key3": 1}
undecorated = [a, b, c]
def compare_key(my_dict):
value = my_dict.get('key2')
try:
result = int(value.split()[0])
except:
result = 0
return result
undecorated.sort(key=compare_key)
print(undecorated)