sharing dictionary data between callbacks in plotly-dash

Viewed 356

I'd like to share dictionary data between callbacks. so I am using dcc.Store() from below tutorial

https://dash.plotly.com/sharing-data-between-callbacks

However I got an error of AttributeError: 'dict' object has no attribute 'to_json'. so it looks like I cannot use to_json with dictionary data.


@app.callback(
    [
    Output("well-table", "data"),
    Output('stored-shared-data-time-dict','data'),
    Output('stored-shared-data-prod-trajectory-dict','data'),
    Output('stored-shared-data-cross-section-list','data'),  
    Output('stored-shared-data-conformance-trajectory-dict','data'),
    ],
    [
    Input('load-area-data','n_clicks'),
    ],
    [
     State("select-area-dropdown", "value"),
     State('read-existing-data-radio','value'),
    ],
)

def change_area_data(n_clicks,area,read_existing_radio):

...
    return (datatable_thisarea,
            df_timedata_dict.to_json(date_format='iso', orient='split'),
            df_prod_trajectory_dict.to_json(date_format='iso', orient='split'),
            df_cross_section_dict_list.to_json(date_format='iso', orient='split'),
            df_conformance_trajectory_dict.to_json(date_format='iso', orient='split'),
           )

     52 
     53     return (datatable_thisarea,
---> 54             df_timedata_dict.to_json(date_format='iso', orient='split'),
        df_timedata_dict.to_json = undefined
        global date_format = undefined
        global orient = undefined
     55             df_prod_trajectory_dict.to_json(date_format='iso', orient='split'),
     56             df_cross_section_dict_list.to_json(date_format='iso', orient='split'),

AttributeError: 'dict' object has no attribute 'to_json

In the above website, it did mention:

Example 1 - Storing Data in the Browser with dcc.Store To save data in the user's browser's session:

The data has to be converted to a string like JSON or base64 encoded binary data for storage

so I change to_json to use base64 encode, then I got another error of TypeError: a bytes-like object is required, not 'dict'.


import base64

def change_area_data(n_clicks,area,read_existing_radio):

...
    return (datatable_thisarea,
            base64.b64encode(df_timedata_dict), 
            base64.b64encode(df_prod_trajectory_dict),  
            base64.b64encode(df_cross_section_dict_list),  
            base64.b64encode(df_conformance_trajectory_dict) 
           )

TypeError: a bytes-like object is required, not 'dict'

so so how to share the dictionary data between callback? I have to use dictionary which contains lots of dataframe with keys. Thanks

1 Answers

To convert the python dictionary to json, try using:

import json
json.dumps(name_of_dictionary)

Storing data with dcc.Store should then function as intended.

Related