如何在变量后命名Python字典?

时间:2018-02-04 22:07:48

标签: python python-3.x dictionary

我正在尝试从coinmarketcap API创建货币信息的dicts,并在货币符号后面命名每个dict。最终目标:

# 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

但是,当我收到coinMarketCapTicker ['symbol']并且它是一个字符串“BTC”时,我很难从该值创建一个名为BTC的字典。

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

这使得一个名为'tickerSymbol'的字典被覆盖了每个符号,而不是名为BTC,ETH,LTC等的字典

我试过这个,但是它们不起作用:

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

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

我有点困惑,有什么想法吗?

1 个答案:

答案 0 :(得分:1)

最终,解决这个问题的一种方法是为每个符号设置一个字典,其中包含所有细节,一个字典与其中的每个符号字典相匹配。

我将dict-of-dicts命名为'ticker',因此这会在名为'ticker'的主目录dict中创建一个名为'symbol'的dict。整个符号dicts用作股票代码[''],个别元素用作股票代码[''] [“”]

在实践中我发布的代码:

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

在循环中,用符号dicts 填充滚动条,同时填写符号dicts。就在休息之前,a:

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

输出'148.227'(Litecoin的当前美元价格),显示从API Feed中提取的随机符号中的数据已正确存储并可用。