Initialize a Python dictionnary with another dictionnary

Viewed 56

I would like to initialise a dictionary and always assign an empty data structure to each key which are then later used.

This is the result and behaviour I would like:

data = {
    "record" : {
        "fields_array" : [],
        "df" : pd.DataFrame(),
        "df_fields" : pd.DataFrame(columns = ["name", "units", "field_type", "base_type", "type"]),
        "rows" : []
    },
    "device_info" : {
        "fields_array" : [],
        "df" : pd.DataFrame(),
        "df_fields" : pd.DataFrame(columns = ["name", "units", "field_type", "base_type", "type"]),
        "rows" : []
    },
}

So each key refers to an unique DataFrame or array.

I wanted to simply my code like this:

data_struct = {  
        "fields_array" : [],
        "df" : pd.DataFrame(),
        "df_fields" : pd.DataFrame(columns = ["name", "units", "field_type", "base_type", "type"]),
        "rows" : []
}

data = {
    "record" : data_struct,
    "device_info" : data_struct,
}

However, if I now use data["record"]["df"] or data["device_info"]["df"], they refer to the same DataFrame.

Why is this behaviour and how can I solve this problem? I have to add many more keys to the data dictionary.

2 Answers

You can use a collections.defaultdict:

data = defaultdict(lambda: {  
    "fields_array" : [],
    "df" : pd.DataFrame(),
    "df_fields" : pd.DataFrame(columns = ["name", "units", "field_type", "base_type", "type"]),
    "rows" : []
})

And then just access any keys:

data['record']
data['device_info']

Use deepcopy

data = {
    "record" : deepcopy(data_struct),
    "device_info" : deepcopy(data_struct),
}
Related