Zach
Zach

Reputation: 58

How to set dictionary values to zero in Julia

I would like to set all the values of a dictionary to zero. In Python you can use the .fromkeys() function to do this (see this SO question). How can this be done in Julia?

Upvotes: 2

Views: 1165

Answers (3)

rafak
rafak

Reputation: 5551

The replace function comes to mind. It takes a function as first argument that takes a pair as argument and returns the modified pair:

d_new = replace(kv -> kv[1] => 0, d)

Here, each pair kv from d is replaced by kv[1] => 0, where kv[1] is the key and 0 the new associated value. Note that the mutating variant replace! is also available for in-place replacement.

EDIT: another possibility when the dictionary has to be mutated is:

map!(x->0, values(d))

Upvotes: 2

Andrej Oskin
Andrej Oskin

Reputation: 2332

Not quite the answer to your question, but it may be interesting for you to consider using Dictionaries.jl package, which provides more convenient means to work with dictionaries than Base Dict.

For example, in Dictionaries.jl notation your question can be solved as follows

using Dictionaries

d = dictionary(['a' => 1, 'b' => 2])

map(zero, d)

Upvotes: 2

Zach
Zach

Reputation: 58

I found the answer to my own question. As mentioned in the Julia docs, dictionaries can be created using generators. So you can copy the keys of the original Dict and assign all the values to be 0 like so

d_new = Dict(i => 0 for i in keys(d))

See also this forum post.

Upvotes: 1

Related Questions