Page 1 of 1

Syntax for dictionary in Script action?

Posted: 25 Oct 2018 19:57
by Nemisorg
Hi there,

Is there any way i can create a dictionary in the Script action?

In Python the syntax would be like this:
dict = {key1: value1, key2: value2}

Thanks

Re: Syntax for dictionary in Script action?

Posted: 26 Oct 2018 11:59
by Helios
Hi,

are you looking for this?

Code: Select all

Map newMapFromValues(String key1, Object value1, ...)
Returns a new map initialized to contain the specified keys and values.

Re: Syntax for dictionary in Script action?

Posted: 26 Oct 2018 12:43
by Nemisorg
Yes! Thanx

Re: Syntax for dictionary in Script action?

Posted: 28 Oct 2018 18:03
by Helios
I just learned that Automagic supports JSON.
So we can do the following:

Code: Select all

dict = fromJSON('{"key1": "value1", "key2": "value2", "key3integer": 123, "key4boolean":  true}')
Please note the nesting quotation marks (outer single quotes, double quotes for strings)


This post is just for the record 8-)

Re: Syntax for dictionary in Script action?

Posted: 28 Oct 2018 18:34
by Desmanto
@Helios : you don't need to create the json, just directly create the map. Map object is equivalent to dictionary in python. I always make it new line for each key, for better indentation.

Code: Select all

dict = newMapFromValues(
"key1", "value1",
"key2", "value2",
"key3integer", 123,
"key4boolean", true);
Each value can be access by querying the key. For example, to access "value2", use dict["key2"]

Re: Syntax for dictionary in Script action?

Posted: 28 Oct 2018 19:06
by Helios
@Desmanto You are totally right. In case you need a simple map, the newMapFromValues() function is sufficient.

But in case you want to have a more complex object, e.g.

Code: Select all

obj = fromJSON( '{"key1": [1, 2, 3, 4], "key2": {"sub1": true, "sub2": false} }' )
vs.

Code: Select all

obj = newMapFromValues( "key1", newList(1, 2, 3, 4), "key2", newMapFromValues("sub1", true, "sub2", false))
I find the first solution better to read.
Of course, by using the second approach with newlines + indention, it will be easier to read - but still - it's more text to type :lol: