如何在python中将list中的值赋给键以创建字典

2024-05-08 09:25:43 发布

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

我有一个键列表和值列表。你知道吗

['OpenInterest_x', 'Change in Open Interest  x', 'LTP_x', 'NetChange_x', 'Volume_x', 'BidQty_x', 'BidPrice_x', 'OfferPrice_x', 'OfferQty_x', 'Strike Price', 'BidQty', 'BidPrice', 'OfferPrice', 'OfferQty', 'Volume', 'NetChange', 'LTP', 'OpenInterest', 'Change in Open Interest'
]

[
['150', '150', '1,070.00', '-928.90', '2', '450', '1,097.20', '1,314.15', '1,875', '4500.00', '375', '3.20', '10.25', '75', '-', '-', '-', '-', '-'], 
['-', '-', '-', '-', '-', '150', '1,001.90', '1,056.15', '150', '4600.00', '75', '7.00', '17.80', '150', '4', '-7.55', '10.00', '1,350', '300']
]

我有兴趣从两本字典中选一本。请注意顺序也很重要。这是我的预期产出。你知道吗

{
    {'OpenInterest_x': '150', ...},
    {'OpenInterest_x': '-', ...},

}

我不能在这里使用zip,因为它会将完整的第一个列表分配给第一个键。最好的方法是什么?你知道吗


Tags: in列表openchangepricevolumestrikeinterest
2条回答

我写了这个,同时杰里米提供了一个非常成功和不错的答案,但我张贴地雷只是作为一个替代或更详细的方法。你知道吗

keys = ['OpenInterest_x', 'Change in Open Interest  x', 'LTP_x', 'NetChange_x', 'Volume_x', 'BidQty_x', 'BidPrice_x', 'OfferPrice_x', 'OfferQty_x', 'Strike Price', 'BidQty', 'BidPrice', 'OfferPrice', 'OfferQty', 'Volume', 'NetChange', 'LTP', 'OpenInterest', 'Change in Open Interest']

values = [
['150', '150', '1,070.00', '-928.90', '2', '450', '1,097.20', '1,314.15', '1,875', '4500.00', '375', '3.20', '10.25', '75', '-', '-', '-', '-', '-'], 
['-', '-', '-', '-', '-', '150', '1,001.90', '1,056.15', '150', '4600.00', '75', '7.00', '17.80', '150', '4', '-7.55', '10.00', '1,350', '300']
]

dict_list = []
for value_list in values:
    my_dict = {item[0]: item[1] for item in zip(keys, value_list)}
    dict_list.append(my_dict)

如果您的第一个列表名为headers,而您的第二个列表仍然是名为values的列表,则可以按以下步骤进行:

list_of_dicts = [dict(zip(headers, sublist)) for sublist in values]

相关问题 更多 >

    热门问题