Nested dicts inside nested dicts, how to automate them?

Viewed 76

I am trying to generate a nested dict, inside another nested dict, but I could only get one step done.

Here is the code i got:

variables = ['CHG', 'Open', 'Close']
assets= ['GOOG', 'FB']
dates =['28-09-2020', '25-09-2020']

dct = {x: dict(zip(assets, '0' * len(assets))) for x in dates}

Gets me:

{'28-09-2020': {'GOOG': '0', 'FB': '0'}, '25-09-2020': {'GOOG': '0', 'FB': '0'}}

How can i generate the dict, with variables inside each asset?

My objective is to get a dict like this:

{'28-09-2020': {'GOOG': {'CHG':0, 'Open':0, 'Close':0}, 'FB': {'CHG':0, 'Open':0, 'Close':0}}, '25-09-2020': {'GOOG': {'CHG':0, 'Open':0, 'Close':0}, 'FB': {'CHG':0, 'Open':0, 'Close':0}}}
4 Answers
{date: {x: dict(zip(variables, '0' * len(variables))) for x in assets} for date in dates}

Output

{'28-09-2020': {'GOOG': {'CHG': '0', 'Open': '0', 'Close': '0'},
  'FB': {'CHG': '0', 'Open': '0', 'Close': '0'}},
 '25-09-2020': {'GOOG': {'CHG': '0', 'Open': '0', 'Close': '0'},
  'FB': {'CHG': '0', 'Open': '0', 'Close': '0'}}}

Let's work this from the inside out.

>>> from itertools import repeat
>>> dict.fromkeys(variables, 0)
{'CHG': 0, 'Open': 0, 'Close': 0}
>>> dict(zip(assets, repeat(_)))
{'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}
>>> dict(zip(dates, repeat(_)))
{'28-09-2020': {'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}, '25-09-2020': {'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}}

So you can use

dct = dict(zip(dates, repeat(dict(zip(assets, repeat(dict.fromkeys(variables, 0)))))))

or in dict comprehension form

dct = {d: {a: dict.fromkeys(variables, 0) for a in assets} for d in dates}
{d: {a: {v:0 for v in variables} for a in assets} for d in dates}

Output

{'28-09-2020': {'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}, 
 '25-09-2020': {'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}}

You could use a NestedDict. First install ndicts

pip install ndicts

Then

from ndicts.ndicts import NestedDict

variables = ['CHG', 'Open', 'Close']
assets= ['GOOG', 'FB']
dates =['28-09-2020', '25-09-2020']

nd = NestedDict.from_product(dates, assets, variables, value=0) 

If you need the result as a dictionary

>>> nd.to_dict()
    {'28-09-2020': {
        'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0},
        'FB': {'CHG': 0, 'Open': 0, 'Close': 0}},
     '25-09-2020': {
        'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0},
        'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}}
Related