Home > database >  accessing matched key values in a dictionary
accessing matched key values in a dictionary

Time:09-25

import os
from requests import Session, Request
import pprint
import json
CMC_API_KEY=os.environ.get('CMC')

parameters={
        'start':1,
        'limit':1500
    }

headers={
        'Accepts':'application/json',
        'X-CMC_PRO_API_KEY':CMC_API_KEY
    }
session=Session()
session.headers.update(headers)
url='https://pro-api.coinmarketcap.com/v1/cryptocurrency/map'
response=session.get(url,params=parameters)
json_file=json.loads(response.text)['data']
for i in range(0,len(json_file)):
    json_file[i]['slug']=json_file[i]['id']
    
[{'first_historical_data': '2013-04-28T18:47:21.000Z',
  'id': 1,
  'is_active': 1,
  'last_historical_data': '2021-09-25T03:49:02.000Z',
  'name': 'Bitcoin',
  'platform': None,
  'rank': 1,
  'slug': 1,
  'symbol': 'BTC'},
 {'first_historical_data': '2013-04-28T18:47:22.000Z',
  'id': 2,
  'is_active': 1,
  'last_historical_data': '2021-09-25T03:49:02.000Z',
  'name': 'Litecoin',
  'platform': None,
  'rank': 17,
  'slug': 2,
  'symbol': 'LTC'}]

Hello, I'm pretty new to programing I wrote this code that matches slugs with their id's but what I don't know how to do is how to access a specific slug to get it's id

CodePudding user response:

I'm not quite sure what you mean by "access a specific slug to get its id". The API returns a list of slugs. If you want to get a slug from its ID, you could do

slug = [s for s in json_file if s["id"] == target_id][0]

Or you could create a dictionary to map the slug IDs to the other information. For example

id_to_slug = {s["id"]: s for s in json_file}
target_slug = id_to_slug[target_id]
  • Related