Reputation: 58
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
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
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