Syntax for dictionary in Script action?

Post your questions and help other users.

Moderator: Martin

Post Reply
Nemisorg
Posts: 6
Joined: 24 Nov 2017 09:17

Syntax for dictionary in Script action?

Post by Nemisorg » 25 Oct 2018 19:57

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

User avatar
Helios
Posts: 17
Joined: 22 Oct 2018 09:41

Re: Syntax for dictionary in Script action?

Post by Helios » 26 Oct 2018 11:59

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.

Nemisorg
Posts: 6
Joined: 24 Nov 2017 09:17

Re: Syntax for dictionary in Script action?

Post by Nemisorg » 26 Oct 2018 12:43

Yes! Thanx

User avatar
Helios
Posts: 17
Joined: 22 Oct 2018 09:41

Re: Syntax for dictionary in Script action?

Post by Helios » 28 Oct 2018 18:03

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-)

User avatar
Desmanto
Posts: 2709
Joined: 21 Jul 2017 17:50

Re: Syntax for dictionary in Script action?

Post by Desmanto » 28 Oct 2018 18:34

@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"]
Index of Automagic useful thread List of my other useful posts (and others')
Xiaomi Redmi Note 5 (whyred), AOSP Extended v6.7 build 20200310 Official, Android Pie 9.0, Rooted.

User avatar
Helios
Posts: 17
Joined: 22 Oct 2018 09:41

Re: Syntax for dictionary in Script action?

Post by Helios » 28 Oct 2018 19:06

@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:

Post Reply