# Dictionary to variables in julia

**URL:** <https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676>\
**Category:** General Usage\
**Created:** [October 3, 2020, 3:59am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676 "2020-10-03T03:59:29Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![libensvivit](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/libensvivit/32/19006_2.png) [@libensvivit](https://discourse.julialang.org/u/libensvivit)\
**Post date:** [October 3, 2020, 3:59am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/1 "2020-10-03T03:59:29Z")

</div>

Hey,  
I will keep the question simple, so I have a dictionary like this:

> my\_dict = Dict(“dataFolder”=\> “my\_data”, “tile\_size” =\> [100, 200], “dims” =\> 20)

and I want the keys to be variables as in my workspace with the corresponding dictionary values:

> dataFolder = “my\_data”  
> tile\_size = [100, 200]  
> dims = 20

My key values are always a string, but the corresponding value may change.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [October 3, 2020, 4:07am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/2 "2020-10-03T04:07:34Z")

</div>

this is ~bad practice in Julia in general, maybe it’s more common in R or something.

can you describe why you need to do this exactly?

---

<div class="post-metadata">

**Author:** ![libensvivit](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/libensvivit/32/19006_2.png) [@libensvivit](https://discourse.julialang.org/u/libensvivit)\
**Post date:** [October 3, 2020, 4:09am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/3 "2020-10-03T04:09:28Z")

</div>

@jling I’m reading a json file that user writes lots of parameters and my Julia program will parse the json and use the parameters as variables.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [October 3, 2020, 4:11am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/4 "2020-10-03T04:11:39Z")

</div>

can’t you just use that json?

---

<div class="post-metadata">

**Author:** ![libensvivit](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/libensvivit/32/19006_2.png) [@libensvivit](https://discourse.julialang.org/u/libensvivit)\
**Post date:** [October 3, 2020, 4:15am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/5 "2020-10-03T04:15:03Z")

</div>

yes.

> my\_dict[“dataFolder”]

would perfectly work but I thought dataFolder as a variable might be more aesthetic? but you are not suggesting, I see. Then I think I will stick with my dictionary.

---

<div class="post-metadata">

**Author:** ![mike](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mike/32/39_2.png) [@mike](https://discourse.julialang.org/u/mike)\
**Post date:** [October 3, 2020, 8:37am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/6 "2020-10-03T08:37:57Z")

</div>

You could make it look a bit more aesthetic by defining a `getproperty` method that gives you slightly nicer `my_dict.dataFolder` syntax instead of `my_dict["dataFolder"]`.

Some limitations of that approach:

- you need `my_dict` to be a type that you’ve defined yourself otherwise defining a

```julia
Base.getproperty(d::Dict, s::Symbol) = ...

```

is **definitely** type piracy since you own neither `Dict`, `Symbol`, nor `getproperty`. So you’d need to wrap `Dict` in your own type:

```julia
 struct MyDict
    dict::Dict
 end
 Base.getproperty(d::MyDict, s::Symbol) = getfield(d, :dict)[string(s)]

```

- The keys of the `Dict` must be valid Julia identifiers, so no dashes, spaces, etc.

You _can_ make values stored in `my_dict` into variables if you use `eval`:

```julia
mod = Module()
for (k, v) in my_dict
    Core.eval(mod, :($(Symbol(k)) = $v))
end
@assert mod.dataFolder == "my_data"

```

But as @jling mentioned above, generally this is _not_ what you should be doing, and in this example doesn’t actually provide any benefit over the `getproperty` approach. It has it’s place at times, but those are pretty limited, and really a last resort.

Another way may be with keyword arguments like:

```julia
julia> function use_variables(;
           tile_size = error("tile_size not provided"),
           dataFolder = error("dataFolder not provided"),
           dims = error("dims not provided"),
           kws... # ignore anything else.
       )
           @show tile_size dataFolder dims # use as variables inside function.
           # ...
       end

julia> use_variables(; (Symbol(k)=>v for (k,v) in my_dict)...)
tile_size = [100, 200]
dataFolder = "my_data"
dims = 20
20

```

Which might work if you only need a predefined set of variables to be handled.

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [October 3, 2020, 9:03am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/7 "2020-10-03T09:03:17Z")

</div>

Don’t do this. It is bad programming practice in any language.

---

<div class="post-metadata">

**Author:** ![jeffreyesun](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreyesun/32/13379_2.png) [@jeffreyesun](https://discourse.julialang.org/u/jeffreyesun)\
**Post date:** [April 9, 2023, 9:20pm UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/8 "2023-04-09T21:20:03Z")

</div>

Hi, just necroposting to say that something like this is easy with the new destructuring syntax. Just do:

```julia
(; dataFolder, tile_size, dims) = my_dict

```

It’s also not bad practice because you are still manually specifying which variables to create. The only issue might that there will be type instability, as the types of the values of `my_dict` are not in general inferred.

---

<div class="post-metadata">

**Author:** ![bjarthur](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bjarthur/32/9638_2.png) [@bjarthur](https://discourse.julialang.org/u/bjarthur)\
**Post date:** [April 10, 2023, 3:24am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/9 "2023-04-10T03:24:54Z")

</div>

[https://github.com/mauro3/UnPack.jl](https://github.com/mauro3/UnPack.jl)

---

<div class="post-metadata">

**Author:** ![dylanxyz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dylanxyz/32/36646_2.png) [@dylanxyz](https://discourse.julialang.org/u/dylanxyz)\
**Post date:** [April 10, 2023, 8:50am UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/10 "2023-04-10T08:50:14Z")

</div>

An alternative to creating a new type and defining `getproperty` is to convert the `Dict` to a `NamedTuple`:

```julia
julia> params = (; [Symbol(k) => v for (k, v) in pairs(my_dict)]... )
(tile_size = [100, 200], dataFolder = "my_data", dims = 20)

julia> params.tile_size
2-element Vector{Int64}:
 100
 200

julia> params.dataFolder
"my_data"

julia> params.dims
20

```

Alternatively, if your `Dict` can be nested (have other `Dict`s as values), for example:

```julia
my_dict_nested = Dict("tile_size" => [100, 200], "dims" => 20, "coords" => Dict("x" => 0, "y" => 1, "z" => 2))

```

You can define a simple function to convert the `Dict` recursively to a `NamedTuple`:

```julia
julia> named_tuple(dict::AbstractDict) = (; [Symbol(k) => named_tuple(v) for (k, v) in pairs(dict)]... )
named_tuple (generic function with 1 method)

julia> named_tuple(x) = x
named_tuple (generic function with 2 methods)

```

And then you can use it like:

```julia
julia> params_nested = named_tuple(my_dict_nested)
(tile_size = [100, 200], dims = 20, coords = (x = 0, z = 2, y = 1))

julia> params_nested.tile_size
2-element Vector{Int64}:
 100
 200

julia> params_nested.coords.x
0

julia> params_nested.coords.y
1

```

---

<div class="post-metadata">

**Author:** ![Salmon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/salmon/32/22968_2.png) [@Salmon](https://discourse.julialang.org/u/Salmon)\
**Post date:** [April 10, 2023, 12:01pm UTC](https://discourse.julialang.org/t/dictionary-to-variables-in-julia/47676/11 "2023-04-10T12:01:37Z")

</div>

This is a nice idea. Personally I also much prefer using `a.x` instead of `a["x"]`.  
I have used this in the past but I was never sure if this is something that one needs to have a bit of caution with do if one does not know that the size of the dict will be small.  
Since large tuples put a lot of stress on the compiler, this might become problematic as well right?  
I wonder if anyone has some wisdom about this.
