I have a dataset from a query binding and I want to turn it into a dictionary in a script. How can I do this? Ignition 7.9.
That’s only in 8.0 I believe, I don’t have that option.
There’s no obvious mapping from dataset to dictionary, so you’ll need to tell us what your dataset looks like and what “shape” you want the resulting dictionary to be.
It’s two columns, I would like the first column to be the key and the second column to be the value.
2 columns and 1 row or multiple rows?
It has multiple rows.
So something like this?
{
"column 1 name" : [values, in, each, row, for, column 1],
"column 2 name" : [values, in, each, row, for, column 2]
}
where the keys are the column name, and the value is an array of the values from the rows of that column?
The dataset is such
id description
1 label1
2 label2
3 label3
...
and so on. I’d like the dictionary to be
{
"1": "label1",
"2": "label2",
"3": "label3",
...
}
Psuedocode-ish:
dict = {}
for row in dataset:
dict[row['id']] = row['description']
You could also just use the indices, i.e. row[0]
and row[1]
.
and I think for the iteration to work it needs to be a PyDataSet, otherwise you’ll have to use some of the other more verbose methods to get the data out.
That was it, thanks.
Hope this helps, for one narrow kind of input as described:
def to_dataset(array_of_objects):
"""Returns a Dataset made from an array of PyDictionaries that have only key-value pairs--no children"""
if array_of_objects == []: raise ValueError("Needs at least one item with keys. Cannot derive keys from an empty array.")
rows = [item.values() for item in array_of_objects]
return system.dataset.toDataSet(array_of_objects[0].keys(), rows)
I've realized since this post (which is 6 years old ) I should just use PyDataSet each row is functionally a dictionary. You can simply do
#all these return a pydataset now
data = system.db.runNamedQuery/runQuery/runPrepQuery(query)
for row in data:
# Access like a dictionary
someValue = row['someVal']
Manually converting to a dictionary is wasting time and computation.
Or if you know your defined columns, then unpacking in the for loop
for (column1, column2, ..., columnN) in data:
# now we have access to the column data directly
If you're gonna put the append
on the same line, you might as well use a comprehension:
rows = [item.values() for item in arrayOfObjects]
Thanks, love it! I've modified my code above.