Ghulam Mohyuddin
Ghulam Mohyuddin

Reputation: 41

How to rename a key in Julia dictionary?

I have a dictionary in Julia:

d = Dict(1 => "A", 2 => "B", 3 => "D")

where I have deleted a key and its value such that:

delete!(d, "1")

Now, I want to re-order the remaining keys as d = Dict(1 => "B", 2 => "D"). How can I do that?

Upvotes: 2

Views: 826

Answers (2)

DNF
DNF

Reputation: 12654

An alternative to using broadcasting for rebuilding the dictionary is to use a generator:

julia> Dict((key-1) => val for (key, val) in d)
Dict{Int64, String} with 2 entries:
  2 => "B"
  3 => "D"

This appears to be faster, too, though this is a very small example to test on:

julia> @btime Dict(keys(d) .- 1 .=> values($d))
  913.333 ns (13 allocations: 944 bytes)

julia> @btime Dict((key-1)=>val for (key, val) in $d)
  150.244 ns (4 allocations: 528 bytes)

Upvotes: 1

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

In your question keys are Ints so the delete operation should be:

delete!(d, 1)

Now to move indices the best way is to rebuild the dictionary:

julia> d2 = Dict(keys(d) .- 1 .=> values(d))
Dict{Int64, String} with 2 entries:
  2 => "D"
  1 => "B"

Upvotes: 2

Related Questions