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)
Answer from Ferdinand Beyer on Stack Overflow
🌐
W3Schools
w3schools.com › python › gloss_python_json_sort.asp
Python JSON Sort
json.dumps(x, indent=4, sort_keys=True) Try it Yourself » · Python JSON Tutorial JSON Parse JSON Convert into JSON Format JSON · ❮ Python Glossary · ★ +1 · Sign in to track progress · REMOVE ADS · PLUS · SPACES · GET CERTIFIED · FOR TEACHERS · BOOTCAMPS · CONTACT US · × · If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com ·
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-json-sort
Python JSON Sort - GeeksforGeeks
July 23, 2025 - In this example, below Python code utilizes the `json` module to parse a JSON array into a list of dictionaries. The script then employs `sorted` with `itemgetter('age')` to sort the list based on the 'age' key.
Top answer
1 of 4
51

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)
2 of 4
35

You can use dict.get() with a default value:

lines = sorted(lines, key=lambda k: k['page'].get('update_time', 0), reverse=True)

Example:

>>> lines = [
...     {"page": {"url": "url1", "update_time": "1415387875"}, "other_key": {}},
...     {"page": {"url": "url2", "update_time": "1415381963"}, "other_key": {}},
...     {"page": {"url": "url3", "update_time": "1415384938"}, "other_key": {}},
...     {"page": {"url": "url4"}, "other_key": {}},
...     {"page": {"url": "url5"}, "other_key": {}}
... ]
>>> lines = sorted(lines, key=lambda k: k['page'].get('update_time', 0), reverse=True)
>>> for line in lines:
...     print line
... 
{'other_key': {}, 'page': {'url': 'url1', 'update_time': '1415387875'}}
{'other_key': {}, 'page': {'url': 'url3', 'update_time': '1415384938'}}
{'other_key': {}, 'page': {'url': 'url2', 'update_time': '1415381963'}}
{'other_key': {}, 'page': {'url': 'url4'}}
{'other_key': {}, 'page': {'url': 'url5'}}

Though, I would still follow the EAFP principle that Ferdinand suggested - this way you would also handle cases when page key is also missing. Much easier to let it fail and handle it than checking all sorts of corner cases.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-sort-json-by-value
Python | Sort JSON by value - GeeksforGeeks
February 12, 2019 - import json data='''{ "Student":[ { "enrollment_no":"9915103000", "name":"JIIT", "subject":[ { "code":"DBMS", "grade":"C" } ] }, { "enrollment_no":"8815103057", "name":"JSS", "subject":[ { "code":"COA", "grade":"A" }, { "code":"CN", "grade":"A+" } ] } ] }''' # Parsing Json object json_parse = json.loads(data) # iterating for it in json_parse['Student']: for y in it['subject']: print(y['code'],y['grade'],it['enrollment_no'],it['name']) Output : DBMS C 9915103000 JIIT COA A 8815103057 JSS CN A+ 8815103057 JSS Code #2 : By using External library such as Pandas (Sorting in Ascending order).
🌐
Linux Hint
linuxhint.com › sort-json-objects-python
How to sort JSON objects in Python – Linux Hint
The JSON file is a very popular medium to exchange data between different types of programming languages. It is a language-independent text-based file format that stores data by using an array and object. The JSON object can be sorted by using built-in python functions, modules, and user-defined ...
🌐
Like Geeks
likegeeks.com › home › python › how to sort json arrays in python
How To Sort JSON Arrays in Python
January 23, 2024 - Learn how to sort JSON arrays in Python with this tutorial. Master sorting techniques for simple, nested, and multi-criteria data arrangements.
🌐
Cach3
w3schools.com.cach3.com › python › gloss_python_json_sort.asp.html
Python JSON Sort - W3Schools
Python HOME Python Intro Python Get Started Python Syntax Python Comments Python Variables Python Data Types Python Numbers Python Casting Python Strings Python Booleans Python Operators Python Lists Python Tuples Python Sets Python Dictionaries Python If...Else Python While Loops Python For Loops Python Functions Python Lambda Python Arrays Python Classes/Objects Python Inheritance Python Iterators Python Scope Python Modules Python Dates Python JSON Python RegEx Python PIP Python Try...Except Python User Input Python String Formatting · Python File Handling Python Read Files Python Write/Cr
🌐
GitHub
github.com › JElchison › sort-json
GitHub - JElchison/sort-json: Python script that sorts a JSON object according to its keys. Useful for diff'ing two JSON files.
user@computer:~$ cat abcd.json { "d": 0, "c": 0, "b": 0, "a": { "a3": 1, "a2": 2, "a1": 3 } } user@computer:~$ diff <(./sort-json.py abc.json) <(./sort-json.py abcd.json) 8c8,9 < "c": 0 --- > "c": 0, > "d": 0 · https://docs.python.org/2/library/json.html#json.dump
Author   JElchison
🌐
W3Schools
w3schools.com › python › ref_list_sort.asp
Python List sort() Method
Python Examples Python Compiler ... Q&A Python Bootcamp Python Certificate Python Training ... The sort() method sorts the list ascending by default....
Find elsewhere
🌐
Medium
varun-verma.medium.com › python-sorting-json-by-keys-30f0d2421136
Python — Sorting JSON by Keys - Verma Varun - Medium
June 17, 2020 - Likewise, if you have JSON that you’d like to sort, you can first convert it to a dictionary and then convert it back to JSON and this time sort it by keys. And this is true for a multi-dimentional dictionary and JSON.
🌐
W3Schools
w3schoolsua.github.io › python › python_json_en.html
Python JSON. Lessons for beginners. W3Schools in English
json.dumps(x, indent=4, sort_keys=True) Try it Yourself » ... Place for your advertisement! ... If you want to report a bug, as well as make an offer for the site, add an ad or advertisement on the site, do not hesitate to email the admin: ... HTML Tutorial CSS Tutorial JavaScript Tutorial SQL Tutorial Python Tutorial PHP Tutorial Bootstrap Tutorial W3.CSS Tutorial AppML Tutorial jQuery Tutorial Angular Tutorial Sass Tutorial Java Tutorial C++ Tutorial C# Tutorial
🌐
W3Schools
w3schools.com › python › python_lists_sort.asp
Python - Sort Lists
Python DSA Lists and Arrays Stacks Queues Linked Lists Hash Tables Trees Binary Trees Binary Search Trees AVL Trees Graphs Linear Search Binary Search Bubble Sort Selection Sort Insertion Sort Quick Sort Counting Sort Radix Sort Merge Sort
🌐
W3Schools
w3schools.com › python › gloss_python_json.asp
Python JSON
Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Python Range Python Arrays Python Iterators Python Modules Python Dates Python Math Python JSON Python RegEx Python PIP Python Try...Except Python String Formatting Python None Python User Input Python VirtualEnv
🌐
Career Karma
careerkarma.com › blog › python › python sort(): a how-to guide
Python Sort(): A How-To Guide | Career Karma
December 1, 2023 - Then we declare a JSON array called students with student names and their test scores. Next, we sort our students using our custom sort function by calling sortFunction as our key. On the final line, our code prints out our sorted list.
🌐
W3Schools
w3schools.io › file › json-python-read-write
How to read and write JSOn file in Python - w3schools
Supply the sort_keys=True parameter to json dumps method ... Open the file with encoding='utf-8'. Supply ensure_ascii=False parameter to json.dumps method ... import json with open('test.json', 'w', encoding='utf-8') as filehandler: ...
🌐
W3Schools
w3schools.com › python › ref_func_sorted.asp
Python sorted() Function
Python Examples Python Compiler ... Python Bootcamp Python Certificate Python Training ... The sorted() function returns a sorted list of the specified iterable object....
🌐
W3Schools
w3schools.com › python › trypython.asp
W3Schools online PYTHON editor
The W3Schools online code editor allows you to edit code and view the result in your browser
🌐
W3Schools
w3schools.com › python › python_challenges_json.asp
Python JSON Code Challenge
Python DSA Lists and Arrays Stacks Queues Linked Lists Hash Tables Trees Binary Trees Binary Search Trees AVL Trees Graphs Linear Search Binary Search Bubble Sort Selection Sort Insertion Sort Quick Sort Counting Sort Radix Sort Merge Sort
🌐
Quora
quora.com › How-can-I-get-JSON-data-and-sort-it-by-Python-1
How to get JSON data and sort it by Python - Quora
Answer (1 of 2): import json import requests url1 = 'https://opendata.epa.gov.tw/ws/Data/ATM00625/?$format=json' html = requests.get(url1) # html.encoding = "BIG5" html.encoding = html.apparent_encoding # print(html.text) jsondata = eval(html.text) # jsondata = json.loads(html.text) for ...
🌐
W3Schools
w3schools.com › python › gloss_python_json_parse.asp
Python JSON Parse
Python JSON Tutorial JSON Convert into JSON Format JSON Sort JSON