Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an Object is an Array or a Dict

Tags:

julia

I'd like to check if var is an Array or a Dict.

typeof(var) == Dict

typeof(var) == Array

But it doesn't work because typeof is too precise: Dict{ASCIIString,Int64}. What's the best way ?

like image 567
Neabfi Avatar asked Feb 23 '16 17:02

Neabfi


People also ask

How do you check if an object is an array?

Determining If an Object Is an Array in Java. In order to determine if an object is an Object is an array in Java, we use the isArray () and getClass () methods. The isArray () method checks whether the passed argument is an array. It returns a boolean value, either true or false.

How to check if a variable is a dictionary in Python?

This function takes two arguments; an object and a class. If the object is an instance of the class or its subclasses, it will return True. If the object is not an instance of the given class, whether direct or indirect, it returns False. Here is a code example to check if the variable is a Dictionary using the isinstance () function:

How to check if a key exists in a Python dictionary?

Use Python to Check if a Key Exists: Python keys Method Python dictionary come with a built-in method that allows us to generate a list-like object that contains all the keys in a dictionary. Conveniently, this is named the.keys () method. Printing out dict.keys () looks like this:

Can an object be used as a dictionary?

Often enough objects are used as dictionaries. Think of a cache object to memoize search results which uses the search strings as property keys. What if a user searches for array_?


Video Answer


1 Answers

If you need a "less precise" check, you may want to consider using the isa() function, like this:

julia> d = Dict([("A", 1), ("B", 2)])
julia> isa(d, Dict)
true
julia> isa(d, Array)
false

julia> a = rand(1,2,3);
julia> isa(a, Dict)
false
julia> isa(a, Array)
true

The isa() function could then be used in control flow constructs, like this:

julia> if isa(d, Dict)
         println("I'm a dictionary!")
       end
I'm a dictionary!

julia> if isa(a, Array)
         println("I'm an array!")
       end
I'm an array!

Note: Tested with Julia 0.4.3

like image 139
summea Avatar answered Oct 13 '22 06:10

summea