# Effectively replace a key in a dictionary

**URL:** https://discourse.julialang.org/t/effectively-replace-a-key-in-a-dictionary/92018
**Category:** General Usage
**Created:** [December 22, 2022, 7:05pm UTC](https://discourse.julialang.org/t/effectively-replace-a-key-in-a-dictionary/92018 "2022-12-22T19:05:37Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![andrey2185](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/andrey2185/32/9889_2.png) [@andrey2185](https://discourse.julialang.org/u/andrey2185)
#### Post date: [December 22, 2022, 7:05pm UTC](https://discourse.julialang.org/t/effectively-replace-a-key-in-a-dictionary/92018/1 "2022-12-22T19:05:37Z")

</div>

Hello, please tell me a way to effectively replace a key in a dictionary, or a package that implements a data structure that allows you to do this, due to a fixed number of key-value pairs

i have too many allocations, it is bad

```julia
using BenchmarkTools

n = 10^6;
d = Dict([i => i for i = 1 : n]...);
keys = [rand(1:n) for i in 1:2*n];

replace_keys(d, n) = for k in keys
    if !haskey(d, k)
        pop!(d)
        d[k] = k
    end
end;

@btime replace_keys(d, keys); # -> 320.215 ms (5998457 allocations: 122.05 MiB) !!!

```

---

<div class="post-metadata">

### Author: ![andrey2185](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/andrey2185/32/9889_2.png) [@andrey2185](https://discourse.julialang.org/u/andrey2185)
#### Post date: [December 22, 2022, 7:16pm UTC](https://discourse.julialang.org/t/effectively-replace-a-key-in-a-dictionary/92018/2 "2022-12-22T19:16:54Z")

</div>

sorry, bug

---

<div class="post-metadata">

### Author: ![andrey2185](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/andrey2185/32/9889_2.png) [@andrey2185](https://discourse.julialang.org/u/andrey2185)
#### Post date: [December 22, 2022, 7:20pm UTC](https://discourse.julialang.org/t/effectively-replace-a-key-in-a-dictionary/92018/3 "2022-12-22T19:20:51Z")

</div>

can i delete this topic?
