3

I am wondering how I can convert a json list to a dictionary using the two values of the JSON objects as the key/value pair. The JSON looks like this:

"test": [
                {
                    "name": "default",
                    "range": "100-1000"
                },
                {
                    "name": "bigger",
                    "range": "1000-10000"
                }
        ]

I basically want the dictionary to use the name as the key and the range as the value. SO the dictionary in this case would be {default:100-1000} {bigger: 1000-10000}

Is that possible?

gaback
  • 638
  • 1
  • 6
  • 13
Pectus Excavatum
  • 3,593
  • 16
  • 47
  • 68

1 Answers1

7

You can first load the JSON string into a dictionary with json.loads. Next you can use dictionary comprehension to post process it:

from json import loads

{ d['name'] : d['range'] for d in loads(json_string)['test'] }

We then obtain:

>>> { d['name'] : d['range'] for d in loads(json_string)['test'] }
{'bigger': '1000-10000', 'default': '100-1000'}

In case there are two sub-dictionaries with the same name, then the last one will be stored in the result.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555