Python 从嵌套字典构建类

Python 从嵌套字典构建类,python,class,dictionary,inheritance,Python,Class,Dictionary,Inheritance,所以我对这一切都是新手,请原谅我的格式不好,只是对行话掌握不牢 简言之,我有一个 coins = requests.get("https://bittrex.com/api/v1.1/public/getcurrencies") 它返回的json()嵌套字典(很抱歉使用了糟糕的措辞)如下所示: { "success" : true, "message" : "", "result" : [{ "Currency" : "BTC", "CurrencyLong"

所以我对这一切都是新手,请原谅我的格式不好,只是对行话掌握不牢

简言之,我有一个

coins = requests.get("https://bittrex.com/api/v1.1/public/getcurrencies")
它返回的json()嵌套字典(很抱歉使用了糟糕的措辞)如下所示:

{
"success" : true,
"message" : "",
"result" : [{
        "Currency" : "BTC",
        "CurrencyLong" : "Bitcoin",
        "MinConfirmation" : 2,
        "TxFee" : 0.00020000,
        "IsActive" : true,
        "CoinType" : "BITCOIN",
        "BaseAddress" : null
    }, {
        "Currency" : "LTC",
        "CurrencyLong" : "Litecoin",
        "MinConfirmation" : 5,
        "TxFee" : 0.00200000,
        "IsActive" : true,
        "CoinType" : "BITCOIN",
        "BaseAddress" : null
    }]
}
class Coinbuilder:
    def __init__(self, cur, curlong):
      self.currency = cur
      self.currency_long = curlong

    @classmethod
    def build_from_dict(coin_b, d):
      attributes = {'Currency', 'CurrencyLong'}
      try:
        class_dct = {a: d[a] for a in attributes}
      except:
        raise ValueError('Input did not contain necessary attributes')
      return coin_b(class_dct['Currency'], class_dct['CurrencyLong'])
# method to retrieve a specific coin from 'list_of_coin_obs[]'
#   we are passing in a parameter, 'coin_abr' to give to our filter
def get_specific_coin_by_abr(coin_abr):
  return next(filter(lambda x: x.currency == coin_abr, list_of_coin_obs)) 
# call our method, which returns a 'CoinBuilder' type  
specific_coin = get_specific_coin_by_abr('BTC')
# print our results to show it worked
print('CurrencyName: ',specific_coin.currency,'CurrencyLong: ',specific_coin.currencyLong)
简言之,我想访问
coins[“result”]
中的每个字典,并用它们构建我自己的值,为每个硬币生成一个类,以便填充继承的代码,如:

class coinbuilder(self, currency, currencyLong, minConfirmation...):
    def __init__(self):
        self.currency = currency
        self.currencyLong = currencyLong
    ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=BTC-" + currency)

我理解这段代码是不正确的,但我想让你知道我要完成什么。对不起,我的措辞很糟糕,我对编程基本上是新手,虽然我对函数有一个基本的了解,但我仍在努力学习行话。

有几种不同的方法可以做到这一点,例如,你可以在你的
\uuuu init\uuu
函数中解析字典

我倾向于使用一个单独的
@classmethod
来处理这个问题,该方法负责解析字典以创建类的实例

大概是这样的:

{
"success" : true,
"message" : "",
"result" : [{
        "Currency" : "BTC",
        "CurrencyLong" : "Bitcoin",
        "MinConfirmation" : 2,
        "TxFee" : 0.00020000,
        "IsActive" : true,
        "CoinType" : "BITCOIN",
        "BaseAddress" : null
    }, {
        "Currency" : "LTC",
        "CurrencyLong" : "Litecoin",
        "MinConfirmation" : 5,
        "TxFee" : 0.00200000,
        "IsActive" : true,
        "CoinType" : "BITCOIN",
        "BaseAddress" : null
    }]
}
class Coinbuilder:
    def __init__(self, cur, curlong):
      self.currency = cur
      self.currency_long = curlong

    @classmethod
    def build_from_dict(coin_b, d):
      attributes = {'Currency', 'CurrencyLong'}
      try:
        class_dct = {a: d[a] for a in attributes}
      except:
        raise ValueError('Input did not contain necessary attributes')
      return coin_b(class_dct['Currency'], class_dct['CurrencyLong'])
# method to retrieve a specific coin from 'list_of_coin_obs[]'
#   we are passing in a parameter, 'coin_abr' to give to our filter
def get_specific_coin_by_abr(coin_abr):
  return next(filter(lambda x: x.currency == coin_abr, list_of_coin_obs)) 
# call our method, which returns a 'CoinBuilder' type  
specific_coin = get_specific_coin_by_abr('BTC')
# print our results to show it worked
print('CurrencyName: ',specific_coin.currency,'CurrencyLong: ',specific_coin.currencyLong)
这样我就不必通过
Coinbuilder
字典来创建类实例,但我有一个简单的方法可以用来解析字典来创建类实例

对于这个简单的示例,我可以执行以下操作:

x = Coinbuilder.build_from_dict({'Currency': 'BTC', 'CurrencyLong': 'Bitcoin'})
或者我可以使用:

y = Coinbuilder('BTC', 'Bitcoin')
并获得两个相等的类实例:

print(x.currency, x.currency_long)
print(y.currency, y.currency_long)
输出:

BTC Bitcoin
BTC Bitcoin
使用示例输入作为指导,一旦编写了
@classmethod
来解析词典,您就可以简单地使用:

my_coins = []
for result in coins['result']:
    my_coins.append(Coinbuilder.build_from_dict(result))
或:


以下是您尝试执行的全部脚本:

import requests
import json

class CoinBuilder:
  def __init__(self,dict):
    self.currency = dict['Currency']
    self.currencyLong = dict['CurrencyLong']
    self.minConfirmation = dict['MinConfirmation']
    self.txFee = dict['TxFee']
    self.isActive = dict['IsActive']
    self.coinType = dict['CoinType']
    self.baseAddress = dict['BaseAddress']
    self.notice = dict['Notice']


coins_response = requests.get("https://bittrex.com/api/v1.1/public/getcurrencies")

all_coins = json.loads(coins_response.content)

list_of_coin_obs = []

for coin in all_coins["result"]:
  list_of_coin_obs.append(CoinBuilder(coin))
此脚本获取响应,然后在
result[]
中的字典中迭代,并从中构建
CoinBuilder
对象。所有创建的对象也存储在一个列表中,
list\u of_coin\u obs[]

然后可以打印前10个结果,例如:

# Print out the first 10 coins
print("First 10 coins:")
for i in range(1,11):
  print(i,") ",list_of_coin_obs[i].currency)
对于本例,这将输出:

First 10 coins:
1 )  LTC
2 )  DOGE
3 )  VTC
4 )  PPC
5 )  FTC
6 )  RDD
7 )  NXT
8 )  DASH
9 )  POT
10 )  BLK
如果您想创建一个方法,通过特定硬币的股票代码查找特定硬币,您可以创建如下内容:

{
"success" : true,
"message" : "",
"result" : [{
        "Currency" : "BTC",
        "CurrencyLong" : "Bitcoin",
        "MinConfirmation" : 2,
        "TxFee" : 0.00020000,
        "IsActive" : true,
        "CoinType" : "BITCOIN",
        "BaseAddress" : null
    }, {
        "Currency" : "LTC",
        "CurrencyLong" : "Litecoin",
        "MinConfirmation" : 5,
        "TxFee" : 0.00200000,
        "IsActive" : true,
        "CoinType" : "BITCOIN",
        "BaseAddress" : null
    }]
}
class Coinbuilder:
    def __init__(self, cur, curlong):
      self.currency = cur
      self.currency_long = curlong

    @classmethod
    def build_from_dict(coin_b, d):
      attributes = {'Currency', 'CurrencyLong'}
      try:
        class_dct = {a: d[a] for a in attributes}
      except:
        raise ValueError('Input did not contain necessary attributes')
      return coin_b(class_dct['Currency'], class_dct['CurrencyLong'])
# method to retrieve a specific coin from 'list_of_coin_obs[]'
#   we are passing in a parameter, 'coin_abr' to give to our filter
def get_specific_coin_by_abr(coin_abr):
  return next(filter(lambda x: x.currency == coin_abr, list_of_coin_obs)) 
# call our method, which returns a 'CoinBuilder' type  
specific_coin = get_specific_coin_by_abr('BTC')
# print our results to show it worked
print('CurrencyName: ',specific_coin.currency,'CurrencyLong: ',specific_coin.currencyLong)
这张照片是:

CurrencyName:  BTC CurrencyLong:  Bitcoin
注意:这是假设您已经创建了
清单,并且与此方法在同一范围内

一个建议是,这里的类名
CoinBuilder
并不完全有意义。类/对象的更好名称应该是
Coin
NamedCurrency
或其他类似名称。我想我知道你想要什么,但这可能更适合你的项目


祝你好运。

到目前为止,这似乎更接近我想要的。虽然当我试图
打印(硬币列表)
它的所有编码?我知道如何使用此设置调用分组,例如打印出硬币和obs.currency的列表,并获取它们的列表,但如何访问每个单独的词典?例如,如果我想调用ADA/Cardano字典作为实例,那么,
list\u of_coin\u obs
将不是字典列表,而是
CoinBuilder
类的对象列表。如果您想访问列表中的每个对象,可以像任何其他列表一样对其进行迭代,例如
for coin in in list\u of coin\u obs:
etc对于您的ADA/Cardano示例,您可以通过多种方式访问列表中的特定对象-一种方式如下:
specific\u coin=next(过滤器(lambda x:x.currency=='ADA',列出硬币的清单(obs))
然后可以使用
print('CurrencyName:',特定的硬币.CurrencyLong,'CurrencyLong:',特定的硬币.CurrencyLong,)打印
谢谢你,我会仔细考虑一下,读一读,以确保我知道到底发生了什么。当然,问你是否需要更多解释Ned的好建议:。你已经处于良好的状态,正试图进入糟糕的状态。。。