Reputation: 41
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
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
Reputation: 42214
In your question keys are Int
s 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