How to get list of keys from Arcade Dictionary

1671
2
Jump to solution
01-18-2022 07:15 AM
DonMorrison1
Occasional Contributor III

I'm getting started with Arcade and can't figure out how to do something that I expect is quite simple. I have a function that returns a Dictionary object.  There is a special case that the caller has to process where the returned Dictionary is empty (ie. it has no keys).  How do I write that in Arcade?  I would think at least I could get an Array of keys then check the length, but I don't see how to do that either

 

var x = Dictionary ()
// My code here
if (??????(x)) {
    // Dict is empty!
}
else
{
    // Dict is not empty 
}

 

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
jcarlson
MVP Esteemed Contributor

It's not as straightforward as you'd hope for. IsEmpty is the go-to function for this for other objects, but a dictionary with no keys still returns a false.

There may be a better way to do this, but if you write an empty for-loop and then return the value of the loop's variable, and empty dictionary will leave it null.

 

var x = Dictionary()

for (var i in x){}

if(IsEmpty(i)){
    return 'Dictionary is empty!'
} else {
    return 'Dictionary is not empty!'
}

 

 And here's an expression to test it out:

 

function DictIsEmpty(dict){
    for (var i in dict){}
    
    if(IsEmpty(i)){
        return 'Dictionary is empty!'
    } else {
        return 'Dictionary is not empty!'
    }
}

var testDicts = [
    Dictionary(),
    Dictionary('key', 'value')
]

for (var d in testDicts){
    Console(DictIsEmpty(testDicts[d]))
}

 

Which prints to the console:

Dictionary is empty!
Dictionary is not empty!
- Josh Carlson
Kendall County GIS

View solution in original post

2 Replies
jcarlson
MVP Esteemed Contributor

It's not as straightforward as you'd hope for. IsEmpty is the go-to function for this for other objects, but a dictionary with no keys still returns a false.

There may be a better way to do this, but if you write an empty for-loop and then return the value of the loop's variable, and empty dictionary will leave it null.

 

var x = Dictionary()

for (var i in x){}

if(IsEmpty(i)){
    return 'Dictionary is empty!'
} else {
    return 'Dictionary is not empty!'
}

 

 And here's an expression to test it out:

 

function DictIsEmpty(dict){
    for (var i in dict){}
    
    if(IsEmpty(i)){
        return 'Dictionary is empty!'
    } else {
        return 'Dictionary is not empty!'
    }
}

var testDicts = [
    Dictionary(),
    Dictionary('key', 'value')
]

for (var d in testDicts){
    Console(DictIsEmpty(testDicts[d]))
}

 

Which prints to the console:

Dictionary is empty!
Dictionary is not empty!
- Josh Carlson
Kendall County GIS
DonMorrison1
Occasional Contributor III

Thanks - this does indeed work - more elegantly than I was considering.  I've been working in Python exclusively for the past 5 years so it's hard to get  used to lots of loops and tricks like this again.