# Search nested namedtuples by key

**URL:** https://discourse.julialang.org/t/search-nested-namedtuples-by-key/84352
**Category:** General Usage
**Tags:** namedtuple, functors, fmap
**Created:** [July 17, 2022, 11:04am UTC](https://discourse.julialang.org/t/search-nested-namedtuples-by-key/84352 "2022-07-17T11:04:28Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![SteffenPL](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/steffenpl/32/206270_2.png) [@SteffenPL](https://discourse.julialang.org/u/SteffenPL)
#### Post date: [July 17, 2022, 9:10pm UTC](https://discourse.julialang.org/t/search-nested-namedtuples-by-key/84352/2 "2022-07-17T21:10:58Z")

</div>

First of all, it might be that `NamedTuple` is not the right type for your application.  
If you want to do a lot of alternation of your data at runtime, then a `Dict` might be better suited, since `NamedTuple`s lead to a bit of compilation each time.

However, the function `propertynames` gives you access to the keys and `values` gives you the values. With these, you can probably do whatever you want with pure Julia. Following your example,  
let’s say you want to recursively replace all occurrences of `gr` with `g`, then you could do

```julia
function replace_gr(nt::NamedTuple)
    new_keys = replace(propertynames(nt), :gr => :g )
    new_values = replace_gr.(values(nt))
    return NamedTuple{new_keys}(new_values)
end
replace_gr(nt) = nt # use multiple dispatch to ignore all non NamedTypes

replace_gr(nt) # -> (g = 'a', f1 = 1, f2 = (g = 'b', f21 = 21))

```

By the way, if you just want to replace a value, you could do `nt_replace_f1 = (; nt..., f1 = 10)`.

---

_[View the full topic](https://discourse.julialang.org/t/search-nested-namedtuples-by-key/84352)._
