I need to print line for line a static json file. I would like to sort this by a key value prior to printing. I have looked at several other examples on stackoverflow, but was unable to find a solution to this particular problem.
My code so far looks like this:
import json
from pprint import pprint
with open('items.json') as data_file:
data = json.load(data_file)
for line in data:
pprint(data)
My json looks like this:
[
{"version": ["2.8.2"], "license": ["GPL"]},
{"version": ["1.8.8"], "license": ["MIT/X11 License"]},
{"version": ["2.8.5"], "license": ["GPL"]},
{"version": ["1.8.9"], "license": ["MIT/X11 License"]}
]
How can I sort it by a key value such as "version" while preserving order? In this way I can determine at which version the license was changed.
Desired output would look like this:
[
{"version": ["1.8.8"], "license": ["MIT/X11 License"]},
{"version": ["1.8.9"], "license": ["MIT/X11 License"]},
{"version": ["2.8.2"], "license": ["GPL"]},
{"version": ["2.8.5"], "license": ["GPL"]}
]
Thank you.
You just need to sort your list of dicts with an appropriate key function. You could use a lambda, but itemgetter
is more efficient.
import json
from pprint import pprint
from operator import itemgetter
data_str = '''\
[
{"version": ["2.8.2"], "license": ["GPL"]},
{"version": ["1.8.8"], "license": ["MIT/X11 License"]},
{"version": ["2.8.5"], "license": ["GPL"]},
{"version": ["1.8.9"], "license": ["MIT/X11 License"]}
]
'''
data = json.loads(data_str)
data.sort(key=itemgetter("version"))
pprint(data)
output
[ {'license': ['MIT/X11 License'], 'version': ['1.8.8']},
{'license': ['MIT/X11 License'], 'version': ['1.8.9']},
{'license': ['GPL'], 'version': ['2.8.2']},
{'license': ['GPL'], 'version': ['2.8.5']}]
It looks like the data is already in dictionary form so something like:
sorted_data = sorted(data, key = lambda x: x['version'])
And then pretty-print that structure.
Edit: you can print the whole structure with one line, by the way:
pprint.pprint(sorted_data, indent=4)
should look pretty nice.
For more information on the lambda expression, have a look at this SO thread: What is key=lambda
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.