我在列表中有dict,我想从值中获取键

2024-10-02 10:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我说‘ETHBTC’,它会给我‘bidPrice’和‘askPrice’的值

My_dic = [{"symbol": "ETHBTC",
"bidPrice": "0.03589300",
"askPrice": "0.03589600"},
{
"symbol": "LTCBTC", 
"bidPrice": "0.00539200",
"askPrice": "0.00539300"}]

Tags: mysymboldicbidpriceaskpriceltcbtcethbtc
3条回答

你可以做:

def get_price(My_dict, symbol):
    for i in My_dict:
        if i["symbol"] == symbol:
            return i["bidPrice"], i["askPrice"]


print(get_price(My_dict, "ETHBTC"))

以下是获得直觉的一种方法:

>>> input_symbol = "ETHBTC"
>>> target_dictionary = [d for d in My_dic if d.get("symbol") == input_symbol][0]
>>> print((target_dictionary.get("bidPrice"), target_dictionary.get("askPrice")))
('0.03589300', '0.03589600')

包装在函数中,如果找不到符号,还应考虑:

def get_prices_for_symbol(sbl):
    target_dictionaries = [d for d in My_dic if d.get("symbol") == sbl]
    if target_dictionaries:
        target_dictionary = target_dictionaries[0]
        return (target_dictionary.get("bidPrice"), target_dictionary.get("askPrice"))
    else:
        raise Exception(f"Symbol {sbl} was not found.")

>>> get_prices_for_symbol("ETHBTC")
('0.03589300', '0.03589600')

>>> get_prices_for_symbol("LTCBTC")
('0.00539200', '0.00539300')

>>> get_prices_for_symbol("test")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in get_prices_for_symbol
Exception: Symbol test was not found.

你可以试试下面的代码

def find(My_dic,sym):
for i in My_dic:
    if i["symbol"]==sym:
        return i["bidPrice"], i["askPrice"]


print(find(My_dic,"ETHBTC"))

相关问题 更多 >

    热门问题