How do I get the size of a dictionary in julia

Viewed 1395

How do I get the size of a Dictionary in julia? size() throws an error.

julia> d = Dict(:x => 1, :y => 2)
julia> size(d)
  MethodError: no method matching size(::Dict{Symbol,Int64})
1 Answers

Use length().

julia> d = Dict(:x => 1, :y => 2)
julia> length(d)
  2

The reason that size() doesn't work is that size is used to give the dimension of a container. From the docs:

size(A::AbstractArray, [dim])

Return a tuple containing the dimensions of A. Optionally you can specify a dimension to just get the length of that dimension.

and

length(A::AbstractArray)

Return the number of elements in the array, defaults to prod(size(A)).

The point with dictionaries is that they do not really have dimensions. You could of course represent them as one dimensional, but that would ignore the fact that the dictionary values can have "dimension", that are not necessarily uniform. For example, what dimensions should this dictionary then have? Two? Users might incorrectly assume they could access dict[:a][1]:

julia> dict = Dict(:a => 1, :b => [1, 2])
Dict{Symbol,Any} with 2 entries:
  :a => 1
  :b => [1, 2]
Related