Dynamically reference a map key

I have a map:

@legacy %{
    wooabsa:                    "woocommerce_gateway_absa",
    woocommerce_absa:           "woocommerce_gateway_absa",
    woompesa:                   "woocommerce_gateway_mpesa",
    woocommerce_mpesa:          "woocommerce_gateway_mpesa",
    wookopokopo:                "woocommerce_gateway_kopokopo",
    woocommerce_kopokopo:       "woocommerce_gateway_kopokopo",
    givempesa:                  "mpesa_for_givewp",
  }

In PHP, I could reference a map (an object) dynamically:

$legacy = (object) array(
    'wooabsa'                    => 'woocommerce_gateway_absa',
    'woocommerce_absa'           => 'woocommerce_gateway_absa',
    'woompesa'                   => 'woocommerce_gateway_mpesa',
    'woocommerce_mpesa'          => 'woocommerce_gateway_mpesa',
    'wookopokopo'                => 'woocommerce_gateway_kopokopo',
    'woocommerce_kopokopo'       => 'woocommerce_gateway_kopokopo',
    'givempesa'                  => 'mpesa_for_givewp',
  );
$get_dynamically = "wooabsa"
$value = $legacy->{$get_dynamically} # value would be woocommerce_gateway_absa

How can I dynamically set an atom… or the map key?

I have tried the following (each line is a separate try):

p = data.payload.l # input to the program
IO.puts("#{p} = " <> @legacy[:"woocommerce_absa"]) # works: mpesa_for_givewp = woocommerce_gateway_absa
IO.puts("#{p} = " <> "@legacy[:#{p}]") # works: mpesa_for_givewp = @legacy[:mpesa_for_givewp]
IO.puts("#{p} = " <> Map.get( @legacy, p )) # ArgumentError
IO.puts("#{p} = " <> Map.get( @legacy, ":#{p}" )) # ArgumentError
IO.puts("#{p} = " <> @legacy[:"#{p}"]) # ArgumentError
IO.puts("#{p} = " <> @legacy[":#{p}"]) # ArgumentError
IO.puts("#{p} = " <> @legacy[String.to_atom(p)]) # ArgumentError
# The ArgumentError
** (ArgumentError) construction of binary failed: segment 3 of type 'binary': expected a binary but got: nil

Is there a way to dynamically reference an atom map key?

Please disregard… I’ve just seen my mistake… p == mpesa_for_givewp which does not exist in the map…

Can you show the actual value of the p variable?

As you have found out, there are a number of perfectly valid ways to get data from a map with a key that’s stored in a variable.