Skip to content
Advertisement

How do I create a list as a key of a dictionary and add to the in different parts list?

I have a for loop that runs through a CSV file and grabs certain elements and creates a dictionary based on two variables.

Code:

for ind, row in sf1.iterrows():
    sf1_date = row['datekey']
    sf1_ticker = row['ticker']
    company_date[sf1_ticker] = [sf1_date]

I for example during the first iteration of the for loop, sf1_ticker = 'AAPL' and sf1_date = '2020/03/01' and the next time around, sf1_ticker = 'AAPL' and sf1_date = '2020/06/01', how do I make the key of ‘AAPL’ in the dictionary equal to ['2020/03/01', '2020/06/01']

Advertisement

Answer

It appears that when you say “key” you actually mean “value”. The keys for a dictionary are the things that you use to lookup values in the dictionary. In your case ticker is the key and a list of dates are the values, e.g. you want a dictionary that looks like this:

{'AAPL': ['2020/03/01', '2020/06/01'].
 'MSFT': ['2020/04/01', '2020/09/01']}

Here the strings AAPL and MSFT are dictionary keys. The date lists are the values associated with each key.

Your code can not construct such a dictionary because it is assigning a new value to the key. The following code will either create a new key in the dictionary company_date if the key does not already exist in the dictionary, or replace the existing value if the key already exists:

company_date[sf1_ticker] = [sf1_date]

You need to append to a list of values in the dict, rather than replace the current list, if any. There are a couple of ways to do it; dict.setdefault() is one:

company_date = {}
for ind, row in sf1.iterrows():
    sf1_date = row['datekey']
    sf1_ticker = row['ticker']
    company_date.setdefault(sf1_ticker, []).append(sf1_date)

Another way is with a collections.defaultdict of list:

from collections import defaultdict

company_date = defaultdict(list)
for ind, row in sf1.iterrows():
    sf1_date = row['datekey']
    sf1_ticker = row['ticker']
    company_date[sf1_ticker].append(sf1_date)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement