【问题标题】:I have dict in list, I want to get key from value我在列表中有 dict,我想从 value 中获取 key
【发布时间】:2020-08-17 13:30:45
【问题描述】:

假设如果我说“ETHBTC”,它会给我“bidPrice”和“askPrice”的值

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

【问题讨论】:

  • 符号的值是唯一的,或者列表可能包含多个ETHBTC 条目?
  • 不,符号的值在每个字典中都是唯一的

标签: python python-3.x list dictionary


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 为什么没有返回?
  • 调用函数时可能需要传递正确的参数,编辑了我的答案
【解决方案2】:

这是获得直觉的一种方法:

>>> 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.

【讨论】:

    【解决方案3】:

    你可以试试下面的代码;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      相关资源
      最近更新 更多