如何从目录列表中获取值?

2024-05-23 19:40:53 发布

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

list_dicts = [{'Symbol': 'KO', 'Code': 12345, 'Instrument': 'option'},{'Strike': '50', 'Price': 3.95},
{'Symbol': 'KO', 'Code': 67890, 'Instrument': 'option'},{'Strike': '51', 'Price': 6.19},
{'Symbol': 'KO', 'Code': 59684, 'Instrument': 'option'},{'Strike': '52', 'Price': 7.58}]

在这里继续我的虚拟数据

我如何找到一个Strike51的选项及其所有对应的值,即PriceCode


Tags: 数据选项codesymbolpricelistkooption
3条回答

您不需要使用循环,只需使用列表中相应字典的索引即可:

list_of_dicts = [
    {
        'Name': 'John',
        'Surname': 'Johnson'
    }, 
    {
        'Number': 123,
        'Birthday': 1960
    }
]

name = list_of_dicts[0]['Name']
birth_year = list_of_dicts[1]['Birthday']
print(f"{name}'s birth year is {birth_year}")

输出:

John's birth year is 1960

如果您仅使用该列表(或假设所有其他输入都是以这种方式格式化的),则可以通过列表索引然后通过dict索引进行访问,如下所示:

print(dict_list[0]['Name'])  # outputs John
print(dict_list[1]['Birthday'])  # outputs 1960

然而,正如您在回答中的评论所说,最好将列表中的所有dict合并到一个列表中,例如{'Name': 'John', 'Surname': 'Johnson', 'Number': 123, 'Birthday': 1960},因为这样您只需通过dicts['Name']dicts['Birthday']即可访问它

从列表或字典中提取信息有两种基本方法。第一个是一个简单的循环,用于查找所需的项。第二种理解可能更简洁、更具表现力,但并不总是清晰

如果一个列表中的字典实际上是分开的(多个字典组成[您称之为单个数据单元],那么循环解决方案可能是最容易理解的

在此假设每个数据单元始终有一对字典,其形式与问题中当前的形式相同:

list_dicts = [
    {'Symbol': 'KO', 'Code': 12345, 'Instrument': 'option'},
        {'Strike': '50', 'Price': 3.95},
    {'Symbol': 'KO', 'Code': 67890, 'Instrument': 'option'},
        {'Strike': '51', 'Price': 6.19},
    {'Symbol': 'KO', 'Code': 59684, 'Instrument': 'option'},
        {'Strike': '52', 'Price': 7.58}
]

找到与给定罢工值匹配的所有价格和代码值的简单解决方案如下(在一个完整的程序中,您可以使用它):

list_dicts = [
    {'Symbol': 'KO', 'Code': 12345, 'Instrument': 'option'},
        {'Strike': '50', 'Price': 3.95},
    {'Symbol': 'KO', 'Code': 67890, 'Instrument': 'option'},
        {'Strike': '51', 'Price': 6.19},
    {'Symbol': 'KO', 'Code': 59684, 'Instrument': 'option'},
        {'Strike': '52', 'Price': 7.58},
    {'Symbol': 'KO', 'Code': 99999, 'Instrument': 'option'},
        {'Strike': '51', 'Price': 9.99},
]

def getPriceCodeList(strike, db):
    retList = []
    for idx in range(0, len(db), 2):
        if db[idx+1]["Strike"] == strike:
            retList += [(db[idx+1]["Price"], db[idx]["Code"])]
    return retList

print(getPriceCodeList('51', list_dicts))

这将返回所需数据的元组列表,例如罢工值为51

[(6.19, 67890), (9.99, 99999)]

相关问题 更多 >