Reputation: 9212
I have a list of keys and list of list of values.
['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']
]
I am interested to create a dictionary out of two. Please note order is also important. This is my expected output.
{
{'OpenInterest_x': '150', ...},
{'OpenInterest_x': '-', ...},
}
I can't use zip here because it will assign the complete first list to first key. What is the best way to do this?
Upvotes: 1
Views: 972
Reputation: 12027
I had wrote this and in the mean time Jeremy provided a very succient and nice answer however i have posted mines just as an alternative or more verbose method.
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)
Upvotes: 1
Reputation: 423
If your first list is called headers
, and your second list remains a list of lists called values
, you can proceed as follows:
list_of_dicts = [dict(zip(headers, sublist)) for sublist in values]
Upvotes: 7