Nelson
Nelson

Reputation: 65

Filter information in python dictionaries dynamically

Filter information in python dictionaries dynamically

Hello first of all say that I am understanding how to filter information in python dictionaries from a JSON to later write them in a JSON file for it I take a regular workflow and I am leaving that we do not always know exactly what we must iterate to illustrate a simple but real life example.

The work flow

The example

for this I am using the apin of CoinMarketCap and this is the data structure:

{
  "data": {
    "1": {
      "id": 1,
      "name": "Bitcoin",
      "symbol": "BTC",
      "website_slug": "bitcoin",
      "rank": 1,
      "circulating_supply": 17168112.0,
      "total_supply": 17168112.0,
      "max_supply": 21000000.0,
      "quotes": {
          "USD": {
          "price": 8159.91,
          "volume_24h": 6805930000.0,
          "market_cap": 140090248790.0,
          "percent_change_1h": -0.65,
          "percent_change_24h": 5.84,
          "percent_change_7d": 18.14
        }
      },
      "last_updated": 1532445803
    },
    "1027": {
      "id": 1027,
      "name": "Ethereum",
      "symbol": "ETH",
      "website_slug": "ethereum",
      "rank": 2,
      "circulating_supply": 100891486.0,
      "total_supply": 100891486.0,
      "max_supply": null,
      "quotes": {
        "USD": {
          "price": 472.418,
          "volume_24h": 2187530000.0,
          "market_cap": 47662953974.0,
          "percent_change_1h": -1.42,
          "percent_change_24h": 2.14,
          "percent_change_7d": -1.83
        }
      },
      "last_updated": 1532445813
    },
    "52": {
      "id": 52,
      "name": "XRP",
      "symbol": "XRP",
      "website_slug": "ripple",
      "rank": 3,
      "circulating_supply": 39315683476.0,
      "total_supply": 99991900487.0,
      "max_supply": 100000000000.0,
      "quotes": {
        "USD": {
          "price": 0.458599,
          "volume_24h": 305718000.0,
          "market_cap": 18030133126.0,
          "percent_change_1h": -1.22,
          "percent_change_24h": 1.69,
          "percent_change_7d": -5.25
        }
      },
      "last_updated": 1532445797
    },
  "metadata": {
    "timestamp": 1532445415,
    "num_cryptocurrencies": 1664,
    "error": null
  }
}    

As you can see are nested dictionaries and there comes a point where you can not iterate explicitly, we must do it dynamically otherwise we should know the id of the crypto currency.

We start the exploration of the dictionaries:

#!/usr/bin/python3

import json
import requests

response = requests.get("https://api.coinmarketcap.com/v2/ticker/")
data = json.loads(response.text)


def keep(data):
    for i in data['data'].key():
        print(i)


keep(data)    

As you can see this is the complex part to iterate.

I managed to get rid of the complex part to get the Top10 of cryptocurrencies:

#!/usr/bin/python3

import json
import requests

response = requests.get("https://api.coinmarketcap.com/v2/ticker/")
data = json.loads(response.text)


def keep(data):
    for i in data['data'].values():
    if i['rank'] <= 10:
        print(json.dumps(i, indent=4))


keep(data)    

But I can not write it to a JSON file, I hope you can help me, thanks in advance.

Upvotes: 0

Views: 134

Answers (1)

user2906838
user2906838

Reputation: 1178

this is what you want to do:

import json
import requests

response = requests.get("https://api.coinmarketcap.com/v2/ticker/")
data = json.loads(response.text)

finallist=[]
def keep(data):
    for i in data['data'].values():
        if i['rank'] <= 10:
            finallist.append(i)


keep(data) 
#jsondata = json.dumps(finallist)
with open('data1sk.json', 'w') as outfile:
    json.dump(finallist, outfile)

This should give your desired result, but you didn't tell, what was not working in your case clearly. However, this is the solution you may try.

Upvotes: 1

Related Questions