Mark Corrigan
Mark Corrigan

Reputation: 554

Two Lists Into One Dictionary Python

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.

Upvotes: 0

Views: 92

Answers (3)

mhawke
mhawke

Reputation: 87124

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,

Upvotes: 2

Andrew Jaffe
Andrew Jaffe

Reputation: 27097

What do you actually want to do?

Are dates and closes the same length and you want to make a dictionary with dates as the keys and closes as the values like {dates[0]: closes[0], dates[1]: closes[1], ...}

If so, you can use the fact that you can construct a dictionary out of a list of (key, value) pairs by making that list using zip:

 dict2write = dict(zip(dates, closes)) 

But if that's not what you want, if you want 'date' and 'close' to be the keys, then it's even easier:

dict2write = {'date': dates, 'close': closes}

(Note as an aside that the "dictionary" in your question, {'date', 'close'}, is not a dictionary, but a set.)

Or do you want something yet different?

Upvotes: 0

ex0ns
ex0ns

Reputation: 1116

A dictionary is a key/value pair, are you looking for that:

dict2write = {}
dict2write['date'] = dates
dict2write['close'] = closes

Or am I missing something ?

Upvotes: 1

Related Questions