geeklimit
geeklimit

Reputation: 33

How do I name a Python dictionary after a variable?

I'm attempting to create dicts of currency information from the coinmarketcap API and name each dict after the currency symbol. End goal:

# see coinmarketcap data entered into the dict
print(BTC['price']  + "\t$" + BTC['marketCap'])

# add arbitrary data to the BTC dict that other dicts might not have
BTC['founder'] = "Satoshi Nakamoto"

# see data from multiple sources in any given dict
print(BTC['symbol']  + " was founded by " + BTC['founder'])
print(LTC['symbol']  + " " + LTC['isMineable']  + " mineable")

BTC was founded by Satoshi Nakamoto
LTC is mineable

However, when I get coinMarketCapTicker['symbol'], and it's a string "BTC", I'm having a hard time creating a dict called BTC from that value.

import requests
import json

tickerURL = "https://api.coinmarketcap.com/v1/ticker/?limit=100"
request = requests.get(tickerURL)
coinMarketCapTicker = request.json()

while True:
    for x in coinMarketCapTicker

        tickerSymbol = x['symbol']

        # load current symbol's dict with the rest of the data from the API
        tickerSymbol = {"symbol" : x['symbol'], "price" : x['price_usd'], "marketCap" : x['market_cap_usd']}

    break

This makes a dict called 'tickerSymbol' that gets overwritten for every symbol, instead of dicts named BTC, ETH, LTC, etc

I've tried this instead, but they don't work:

x['symbol'] = {"symbol" : x['symbol'], "price" : x['price_usd'], "marketCap" : x['market_cap_usd']}

and

str(x['symbol']) = {"symbol" : x['symbol'], "price" : x['price_usd'], "marketCap" : x['market_cap_usd']}

I'm a little stuck, any ideas?

Upvotes: 1

Views: 104

Answers (1)

geeklimit
geeklimit

Reputation: 33

Ultimately, one way to solve this is by having one dictionary for every symbol with all of the details inside, and one dictionary a level up with every symbol dictionary within it.

I named the dict-of-dicts 'ticker', so this creates a dict named with 'symbol'...inside a master directory dict called 'ticker'. Entire symbol dicts are used as ticker[''], and individual elements as ticker[''][""]

In practice with the code I posted:

ticker[x['symbol']] = {"symbol" : x['symbol'], "price" : x['price_usd'], "marketCap" : x['market_cap_usd']}

is in the loop, populating ticker with symbol dicts and filling in the symbol dicts at the same time. Just before the break, a:

print(ticker['LTC']["price"])

outputs '148.227' (the current USD price of Litecoin), which shows data from a random symbol extracted from the API feed is correctly stored and available.

Upvotes: 1

Related Questions