If I have two lists
dates = []
closes = []
And I have one dictionary
dict2write = {'date', 'close'}
How do I fill the dictionary with the two lists? I'm going to write the dictionary into a csv.
To make a dictionary use zip()
to form tuples and then dict()
to create the dictionary.
>>> dates = ['2014-07-31', '2013-11-22', '2014-01-01']
>>> closes = ['what', 'is', 'this?']
>>> zip(dates, closes)
[('2014-07-31', 'what'), ('2013-11-22', 'is'), ('2014-01-01', 'this?')]
>>> d = dict(zip(dates, closes))
>>> d
{'2013-11-22': 'is', '2014-07-31': 'what', '2014-01-01': 'this?'}
But if you want to write the data to a CSV file, you don't need to create dictionaries, you just need to zip the lists.
import csv
with open('data.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(zip(dates, closes))
Output in data.csv is:
2014-07-31,what
2013-11-22,is
2014-01-01,this?
One other thing worth mentioning, if the lengths of the lists vary you can use itertools.izip_longest()
to zip the lists. e.g.
import csv
from itertools import izip_longest
dates = ['2014-07-31', '2013-11-22', '2014-01-01']
closes = ["what's", 'this?']
with open('data.csv', 'w') as f:
csv.writer(f).writerows(izip_longest(dates, closes))
This will leave the missing columns empty in the resultant CSV file:
2014-07-31,what's
2013-11-22,this?
2014-01-01,
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments