I have a dictionary that represents one row of data from a table, the keys for the dictionary items are the column headers and the values are the value for that specific row. I am trying to write a method in scripting that will convert the dictionary into a dataset that can be used with power tables on the ignition GUI side for the user to see. I am trying to use the system.dataset.toDataSet(headers, row) method to do this. to create the headers var I do the following, headers = list(dict_in.keys()). to create the row I am trying to create a list of list's where each child list is something like [key, value]. am I thinking of this correctly? Any advice would be appreciated.
The data that you pass to the toDataSet function needs to be a list of lists where each inner list is the values for one row in the same order as the headers that you pass in. There is probably a cleaner way to do this, but the following should work:
rowData = []
headers = []
for key, value in dict_in.iteritems():
headers.append(key)
rowData.append(value)
dataset = system.dataset.toDataSet(headers, [rowData])
I'm a bit confused by your question because there seems to be little utility in taking a single dictionary and making it a DataSet. If you truly need just a single dictionary converted, the supplied approach above should be good enough.
If you need to convert a list of dictionaries, you an use the approach below. There are some assumptions being made in my example (like homogenous dictionaries), but this should be a general approach:
def transform(self, value, quality, timestamp):
headers = value[0].keys() # assumes all row have the exact same keys
data = []
for row in value:
data.append([row[header] for header in headers])
return system.dataset.toDataSet(headers, data)
I'll suggest this:
headers = dict_in.keys()
data = dict_in.values()
They may or may not need to be wrapped in a list()
wasn't sure if they would be in the same order, but looking at the python docs they will be assuming no modifications to the dictionary between calls.