Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python extract values in JSON array to form a new key-value pair

Given an array of JSON objects as:

arr=[{"id": "abc", "value": "123"}, {"id": "xyz", "value": "456"}]

I would like to output a single JSON object like:

new_arr={"abc":123,"xyz":456}

Currently I can extract the elements like arr[0]['id'] but I am wondering what’s the one-liner or better way to form the output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A one-liner to extract the ids and values would be like this:

new_arr = {item['id']: int(item['value']) for item in arr}

as the arr object contains the value as a str you need to convert it to an int(). The rest of the one line similar to a list comprehension with dict as the base element to add to, thereby being a dict comprehension. Though this assumes that all dicts have a id and value combination (which is unknown from your data and am assuming that they always have an id and value)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading