Samuel Leberto
Samuel Leberto

Reputation: 137

Python create dictionary from json values

I currently do an API call to the Steam Web API which gets a json response which looks like this:

{
"response": {
    "globalstats": {
        "heist_success": {
            "total": "58932654920",
            "history": [
                {
                    "date": 1486252800,
                    "total": "696574"
                },
                {
                    "date": 1486339200,
                    "total": "357344"
                },
                {
                    "date": 1486425600,
                    "total": "356800"
                },
                {
                    "date": 1486512000,
                    "total": "311056"
                }
            ]

        }
    },
    "result": 1
}

The date is in unix time stamp and the total is an amount. What I want to do is create a dictionary from the values in date and time and not the names. I tried using the following:

dict = dict(data['response']['globalstats']['heist_success']['history'])

But that just created a dict of "date" "total".

How can I create a dict of just the values?

Upvotes: 3

Views: 9614

Answers (2)

Sarath Sadasivan Pillai
Sarath Sadasivan Pillai

Reputation: 7091

You may get the values and make dictionary out of it ,

This is what you may do

Code

d = data['response']['globalstats']['heist_success']['history']
result_dict = dict((i["date"],i["total"]) for i in d)

You may also use dict comprehension if using python version 2.7 or above

result_dict = {i["date"]:i["total"]  for i in d}

Output

{1486252800: '696574',
 1486339200: '357344',
 1486425600: '356800',
 1486512000: '311056'}

Upvotes: 8

Mark Tolonen
Mark Tolonen

Reputation: 177674

You can use a dict comprehension:

D = {h['date']:h['total'] for h in data['response']['globalstats']['heist_success']['history']}

The for will iterate over the list of dicts in history and date and total are selected as the key and value.

Upvotes: 2

Related Questions