I have a file consists of JSON, each a line, and want to sort the file by update_time reversed.
sample JSON file:
{ \"page\": { \"url\": \"url1\", \"
Write a function that uses try...except
to handle the KeyError
, then use this as the key
argument instead of your lambda.
def extract_time(json):
try:
# Also convert to int since update_time will be string. When comparing
# strings, "10" is smaller than "2".
return int(json['page']['update_time'])
except KeyError:
return 0
# lines.sort() is more efficient than lines = lines.sorted()
lines.sort(key=extract_time, reverse=True)