DataTable data input types


I know that DataTable accept list of dicts as input or data=df.to_dict('records')

The example in DataTable reference is as follows:
Example: [ {‘column-1’: 4.5, ‘column-2’: ‘montreal’, ‘column-3’: ‘canada’}, {‘column-1’: 8, ‘column-2’: ‘boston’, ‘column-3’: ‘america’} ]

With this method I can pass a list of dictionaries like:

data_list = [{'Field': 'something', 'Value': 'something else'},
                  {'Field': 'apple', 'Value': 'strawberry'}]

I’m wondering if the following is a possibility. I couldn’t manage to make it work and I think the reason is because DataTable takes information row by row. If you know why this doesn’t work or if there’s a way to make it work, let me know!

FIELDS = ['something', 'apple']
VALUES = ['something else', 'strawberry']

data_list = [{'Field': FIELDS, 'Value': VALUES}]

Thank you!

If I understand you correctly, you have 2 ordered lists and you would like to pass them in as the data for a DataTable? If that is so, just do something like the following:

FIELDS = ['something', 'apple']
VALUES = ['something else', 'strawberry']

data_list = [{'Field': i, 'Value': j} for i,j in zip(FIELDS,VALUES)]

Basically each value needs to have its own label, not a nested values.

You can also just make it a dataframe and then transform it using .to_dict(‘records’) method

df = pd.DataFrame([VALUES], columns = FIELDS)
data = df.to_dict('records')

Thank you! I used to convert to a dataframe but it takes more code to do that because I need in a dictionary form to be used after

I just tried the zip method but unfortunately it doesn’t seem to work. I get empty rows.

This is what I normally use and it works but I thought maybe I wouldn’t need this:

def datatable_data(fields, values):
     list_of_dicts = []
     for each_field, each_value in zip(fields, values):
         small_dict = {'Field': each_field, 'Value': each_value}
     return list_of_dicts