`length.(keys(d))` does not work?

question

#1

Create a dictionary with vector keys:

d = Dict([1,2] => 1.1, [3,2] => 0.1)

Then I want to evalute the length of the keys, so I write:

length.(keys(d))

But this results in an error:

ERROR: MethodError: no method matching size(::Base.KeyIterator{Dict{Array{Int64,1},Float64}})

What is the reason for this? Is this intentional?


#2

This works on master, but not on 0.5.0. You can file an issue on GitHub so that the fix is backported to 0.5.1 if possible.

In the meantime, you can work around this by defining this function:

Base.size(x::Base.KeyIterator) = (length(x),)

#3

Thanks for the reply.


#4

Does

length.(collect(keys(d)))

do what you want?


#5

@giordano Yes, but I expected length.(keys(d)) to work.


#6

AFAIK, broadcast is supposed to work for arrays, tuples and/or scalars, not iterators (that’s what is written in the docstring of broadcast). keys returns an iterator, collect(keys(d)) an array. But I guess you’re advocating for broadcast working with iterators too.


#7

On 0.5 you can get what you want with any of the following

[length(k) for k in keys(d)]
map(length, keys(d))

#8

@pabloferz I know, but it’s longer.