如何从字典中获取特定的值



我正在尝试使用从网站抓取的数据来填充字典,我得到数据,然后我将其分配给字典,当我打印字典时数据显示。我不能只访问字典的一行,我错过了什么?

代码如下:

import requests
from bs4 import BeautifulSoup
print('{:<10} {:<30}'.format('Tiker', 'Price'))
print()
url = 'https://www.coingecko.com/en'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
coin_table = soup.find('div', class_ = 'coingecko-table')
sym = [] 
price = [] 
for coin in coin_table.find_all('tbody'):
rows = coin.find_all('tr')
for row in rows:
token_sym = row.find('span', class_ = 'tw-hidden d-lg-inline font-normal text-3xs ml-2').text.strip()
token_price = row.find('span', {'data-target' : 'price.price'}).text.strip()
sym.append(token_sym)
price.append(token_price)

print('{:<10} {:<30}'.format((token_sym),(token_price)))
data = dict(zip(sym,price))
print(data)

输出:

Tiker      Price
BTC        $44,124
ETH        $3,008.67
USDT       $1.00
BNB        $375.26
ADA        $1.70
XRP        $0.942681
DOGE       $0.255957
USDC       $1.00
DOT        $20.18
UNI        $27.07
BUSD       $1.00
SOL        $40.00
BCH        $598.93
LTC        $163.80
LINK       $24.36
WBTC       $44,081
ICP        $62.06
MATIC      $1.28
ETC        $58.58
XLM        $0.319697
VET        $0.104720
THETA      $6.64
LUNA       $16.00
FIL        $67.32
OKB        $22.29
TRX        $0.081499304270
DAI        $1.00
FTT        $48.11
CUSDC      $0.022222942221
AAVE       $381.38
XMR        $258.06
CETH       $60.28
CDAI       $0.021684507697
EOS        $4.60
CAKE       $18.80
AXS        $69.08
ATOM       $13.65
GRT        $0.793827
SHIB       $0.000007551040
KLAY       $1.43
CRO        $0.138263
NEO        $46.96
BTT        $0.004398147292
AMP        $0.060216111886
MKR        $3,200.18
BSV        $152.82
ALGO       $0.866358
LEO        $2.91
XTZ        $3.27
MIOTA      $0.985600
AVAX       $15.68
CEL        $6.21
EGLD       $125.47
COMP       $445.51
STETH      $2,995.42
KSM        $251.38
HT         $12.63
UST        $1.00
SUSHI      $10.80
DCR        $152.33
HBAR       $0.213998
QNT        $148.47
HOT        $0.010435101561
WAVES      $17.89
RUNE       $6.64
DASH       $172.98
CHZ        $0.330519
HBTC       $43,875
TFUEL      $0.323835
SNX        $10.08
XEM        $0.183840
ZEC        $132.08
XDC        $0.119131
HNT        $15.63
ENJ        $1.51
STX        $1.32
NEAR       $3.09
RVN        $0.139150
YFI        $36,081
TUSD       $1.00
FLOW       $22.20
ZIL        $0.096280701841
IOTX       $0.119378
SAFEMOON   $0.000002055113
TEL        $0.018552432865
CLOUT      $99.89
QTUM       $10.12
BAT        $0.696237
BCHA       $54.61
NEXO       $1.82
MANA       $0.779030
BTG        $57.86
PAX        $1.00
ONE        $0.089852635606
BNT        $3.89
XSUSHI     $12.47
DGB        $0.058679738018
KCS        $10.75
TITAN      $8.35
SC         $0.017170311254
{'BTC': '$44,124', 'ETH': '$3,008.67', 'USDT': '$1.00', 'BNB': '$375.26', 'ADA': '$1.70', 'XRP': '$0.942681', 'DOGE': '$0.255957', 'USDC': '$1.00', 'DOT': '$20.18', 'UNI': '$27.07', 'BUSD': '$1.00', 'SOL': '$40.00', 'BCH': '$598.93', 'LTC': '$163.80', 'LINK': '$24.36', 'WBTC': '$44,081', 'ICP': '$62.06', 'MATIC': '$1.28', 'ETC': '$58.58', 'XLM': '$0.319697', 'VET': '$0.104720', 'THETA': '$6.64', 'LUNA': '$16.00', 'FIL': '$67.32', 'OKB': '$22.29', 'TRX': '$0.081499304270', 'DAI': '$1.00', 'FTT': '$48.11', 'CUSDC': '$0.022222942221', 'AAVE': '$381.38', 'XMR': '$258.06', 'CETH': '$60.28', 'CDAI': '$0.021684507697', 'EOS': '$4.60', 'CAKE': '$18.80', 'AXS': '$69.08', 'ATOM': '$13.65', 'GRT': '$0.793827', 'SHIB': '$0.000007551040', 'KLAY': '$1.43', 'CRO': '$0.138263', 'NEO': '$46.96', 'BTT': '$0.004398147292', 'AMP': '$0.060216111886', 'MKR': '$3,200.18', 'BSV': '$152.82', 'ALGO': '$0.866358', 'LEO': '$2.91', 'XTZ': '$3.27', 'MIOTA': '$0.985600', 'AVAX': '$15.68', 'CEL': '$6.21', 'EGLD': '$125.47', 'COMP': '$445.51', 'STETH': '$2,995.42', 'KSM': '$251.38', 'HT': '$12.63', 'UST': '$1.00', 'SUSHI': '$10.80', 'DCR': '$152.33', 'HBAR': '$0.213998', 'QNT': '$148.47', 'HOT': '$0.010435101561', 'WAVES': '$17.89', 'RUNE': '$6.64', 'DASH': '$172.98', 'CHZ': '$0.330519', 'HBTC': '$43,875', 'TFUEL': '$0.323835', 'SNX': '$10.08', 'XEM': '$0.183840', 'ZEC': '$132.08', 'XDC': '$0.119131', 'HNT': '$15.63', 'ENJ': '$1.51', 'STX': '$1.32', 'NEAR': '$3.09', 'RVN': '$0.139150', 'YFI': '$36,081', 'TUSD': '$1.00', 'FLOW': '$22.20', 'ZIL': '$0.096280701841', 'IOTX': '$0.119378', 'SAFEMOON': '$0.000002055113', 'TEL': '$0.018552432865', 'CLOUT': '$99.89', 'QTUM': '$10.12', 'BAT': '$0.696237', 'BCHA': '$54.61', 'NEXO': '$1.82', 'MANA': '$0.779030', 'BTG': '$57.86', 'PAX': '$1.00', 'ONE': '$0.089852635606', 'BNT': '$3.89', 'XSUSHI': '$12.47', 'DGB': '$0.058679738018', 'KCS': '$10.75', 'TITAN': '$8.35', 'SC': '$0.017170311254'}

预期的结果:

'BTC': '$44,124'

I have try:

print(data)[1]
data.get(0)

如果我去掉zip参数当字典被定义时我得到错误

data = dict(sym,price) TypeError: dict预计最多1个参数有2

也尝试像这样设置字典:

val = dict(((token_sym,token_price,row)for row in rows))

但是只返回最后一个值它不会保存字典中所有的值

字典使用"键"而不是像List对象那样依赖于索引。引用键以获得所需值。

此外,如果你打算遍历每个硬币,而不是使用.append()创建它们的列表,你可能会考虑创建一个字典,因为这会给你更快的查找。

在当前的示例中,您必须遍历整个数据列表并检查字典是否是您想要的。如果你只是创建一个字典,你可以这样做:

coin_results = {}
for coin in coin_table.find_all('tbody'):
rows = coin.find_all('tr')
for row in rows:
token_sym = row.find('span', class_ = 'tw-hidden d-lg-inline font-normal text-3xs ml-2').text.strip()
token_price = row.find('span', {'data-target' : 'price.price'}).text.strip()

# dictionary creation
coin_dict = {token_sym: token_price}
coin_results.update(coin_dict)

这将产生:

# Final dictionary
coin_results = {
'BTC': 'some price data here',
'other coin here': 'some other price data',
...
}
# Access this like: 
coin_results['BTC']
>>> 'some price data here'

使用键访问字典中的值是正常的。即

data['BTC']

(正如xtryingx在评论中提到的)

但是,如果您事先不知道键的名称,但您仍然希望获取第一个键的值,那么您可以将键转换为列表并通过索引访问该新列表:

list(data)[0] # returns 'BTC'

然后用它作为键。

获取值:

print(data["BTC"])

以指定的格式打印第一行

print(f"{list(data.keys())[0]}: {data[list(data.keys())[0]]}")

打印它调用btc

print(f"{'BTC'}: {data['BTC']}"

您还可以将数据格式更改为键:值对列表,例如

[{"BTC": 10000}, {"ETH": 1000}]

这样就可以很容易地调用索引

>>> x = [{"hi": 123}, {"ho":12}]
>>> x[0]
{'hi': 123}

相关内容

  • 没有找到相关文章

最新更新