简体   繁体   中英

I have dict in list, I want to get key from value

Suppose If I will say 'ETHBTC" It will give me values of 'bidPrice' and 'askPrice'

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

You can do:

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"))

Here's one way to get the intuition:

>>> 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')

Wrapped in a function, also taking into account if your symbol is not found:

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.

you can try below code;

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


print(find(My_dic,"ETHBTC"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM