Home > Enterprise >  Creating a dictionary with a loop
Creating a dictionary with a loop

Time:10-13

generic_list = ['A1', 'B2', 'C3', 'D4', 'E5', 'F6']
empty_dict = [{}]
generic_CT_curves_month = [np.datetime64('2022-12-01T00:00:00.000000000'),
                                  np.datetime64('2023-03-01T00:00:00.000000000'),
                                  np.datetime64('2023-05-01T00:00:00.000000000'),
                                  np.datetime64('2023-07-01T00:00:00.000000000'),
                                  np.datetime64('2023-10-01T00:00:00.000000000'),
                                  np.datetime64('2023-12-01T00:00:00.000000000')]
generic_curves_dict = dict(zip(generic_list, empty_dict * 6))
print(generic_curves_dict)
for ticker in generic_curves_dict:
    generic_curves_dict[str(ticker)]['month'] = generic_CT_curves_month[int(ticker[-1])-1]
    
generic_curves_dict

output:

{'A1': {'month': numpy.datetime64('2023-12-01T00:00:00.000000000')},
 'B2': {'month': numpy.datetime64('2023-12-01T00:00:00.000000000')},
 'C3': {'month': numpy.datetime64('2023-12-01T00:00:00.000000000')},
 'D4': {'month': numpy.datetime64('2023-12-01T00:00:00.000000000')},
 'E5': {'month': numpy.datetime64('2023-12-01T00:00:00.000000000')},
 'F6': {'month': numpy.datetime64('2023-12-01T00:00:00.000000000')}}

I want generic_curves_dict['A1']['month'] to call the first date from generic_CT_curves_month and so on. How do I do that?

CodePudding user response:

This was a very good attempt that almost works except for a few tricky details. It boils down to dictionaries being mutable in python, and the fact that empty_dict * 6 copies a reference to the same mutable dictionary 6 times.

In your for loop, generic_CT_curves_month[int(ticker[-1])-1] does give the correct date time, but generic_curves_dict['B1'] refers to a second reference to the same dictionary as generic_curves_dict['A1'] so each cycle overwrites the month value in all 6 dictionaries. (To see this try print([id(d) for d in generic_curves_dict.values()]). It will show that each dict points to the same spot in memory).

There are a few ways to solve this. One would be to define generic_curves_dict in another way:

# generic_curves_dict = dict(zip(generic_list, empty_dict * 6))
generic_curves_dict = dict(zip(generic_list, [{}, {}, {}, {}, {}, {}]))

Alternatively, dict comprehensions could come in handy too.

import numpy as np

generic_list = ['A1', 'B2', 'C3', 'D4', 'E5', 'F6']
generic_CT_curves_month = [np.datetime64('2022-12-01T00:00:00.000000000'),
                                  np.datetime64('2023-03-01T00:00:00.000000000'),
                                  np.datetime64('2023-05-01T00:00:00.000000000'),
                                  np.datetime64('2023-07-01T00:00:00.000000000'),
                                  np.datetime64('2023-10-01T00:00:00.000000000'),
                                  np.datetime64('2023-12-01T00:00:00.000000000')]
generic_curves_dict = {ticker: {"month": generic_CT_curves_month[int(ticker[-1]) - 1]} for ticker in generic_list}
print(generic_curves_dict)

p.s. Are you intentionally stripping the number from the tickers A1 -> 1, etc. or will the dates always be in the same order as the tickers? For this particular example you could also use enumerate to iterate through the index and value of each ticker but not sure if that is a universal solution for your case

import numpy as np

generic_list = ['A1', 'B2', 'C3', 'D4', 'E5', 'F6']
generic_CT_curves_month = [np.datetime64('2022-12-01T00:00:00.000000000'),
                                  np.datetime64('2023-03-01T00:00:00.000000000'),
                                  np.datetime64('2023-05-01T00:00:00.000000000'),
                                  np.datetime64('2023-07-01T00:00:00.000000000'),
                                  np.datetime64('2023-10-01T00:00:00.000000000'),
                                  np.datetime64('2023-12-01T00:00:00.000000000')]
generic_curves_dict = {ticker: {"month": generic_CT_curves_month[i]} for i, ticker in enumerate(generic_list)}
print(generic_curves_dict)

CodePudding user response:

You can use a dictionary comprehension to generate the required generic_curves_dict

Also read more about what the zip function here

generic_curves_dict = {k: dict(month=v) for (k,v) in zip(*[generic_list, generic_CT_curves_month])}

CodePudding user response:

You can use a dictionary comprehension to build this dictionary

generic_curves_dict = {k: {'month': v} for k,v in zip(generic_list, generic_CT_curves_month)}
  • Related