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?

4
  • You want to change a string to an integer..? Maybe you should start by setting your JSON strings to integers. Commented Aug 1, 2017 at 16:07
  • Possible duplicate of Converting JSON String to Dictionary Not List Commented Aug 1, 2017 at 16:08
  • 1
    But in your question, you define two dictionaries as output? Commented Aug 1, 2017 at 16:09
  • 1
    Keyword: dict comprehension. Commented Aug 1, 2017 at 16:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.