Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python create dictionary from json values

Tags:

python

json

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?

like image 903
Samuel Leberto Avatar asked Oct 16 '25 05:10

Samuel Leberto


1 Answers

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'}
like image 81
Sarath Sadasivan Pillai Avatar answered Oct 18 '25 20:10

Sarath Sadasivan Pillai