Pass a key as a variable to create a dictionary

I want to a pass a key as a variable in a dictionary:

iex(1)> a1 = :key1
:key1
iex(2)> %{a1: 123}
%{a1: 123}
iex(3)> %{^a1: 123}
** (SyntaxError) iex:3: syntax error before: a1

iex(3)> %{a1: 123} 
%{a1: 123}
iex(4)> %{a1, 123}
** (SyntaxError) iex:4: syntax error before: '}'

iex(4)> %{a1 123} 
** (SyntaxError) iex:4: syntax error before: '}'

I want this result:

%{key1: 123} 

How can I do it?

A blah: is an atom, it is equal to :blah => as just a shortcut helper. If you want a non-atom, like a binding as a key, then use the full => form, thus:

a1 = :key1
%{a1 => 123}

:slight_smile:

1 Like

You need to use Map.put/3 or its sibblings here:

iex(1)> a1 = :key1
:key1
iex(2)> Map.put(%{}, a1, 123)
%{key1: 123}
iex(3)> %{a1 => 123}
%{key1: 123}

This is because the syntax you are using hides that the key is actually an atom!

%{key: value}

becomes:

%{:key => value}

So the “=>” is universal and associates the left to the right, while “key:” style is shorthand for “key is a literal atom I want to associate with this value”

1 Like

No, it doesn’t!!!