-3

I've done some looking on how I can flip a variable name and that variable's value, but I have come up empty-handed.

What I want

Let me clarify what I would like with an example. Imagine I had a variable called my_variable and it's value would be a string 'my_new_variable'

my_variable = 'my_new_variable'

Is there any way that I can flip these so that it may look like this

my_new_variable = 'my_variable'
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44

4 Answers4

4

A dict is the appropriate way to do this. Driving internal symbol names with data is a strong sign of poor program design. Please use the dict, and refer to XY Problem. External data should drive data relations, but not the internal representation. By doing so, you make your algorithm's structure dependent on the data. Data manipulation should be independent of those specific values.

You can do it;; a little research on this site will give you the references. Don't.

Prune
  • 76,765
  • 14
  • 60
  • 81
3

Should you want to do that, how about

globals()[my_variable] = 'my_variable'
j1-lee
  • 13,764
  • 3
  • 14
  • 26
1

You can try doing this (after installing python-varname):

from varname import nameof
my_variable = 'my_new_variable'
exec("%s = '%s'" % (my_variable, nameof(my_variable))
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28
  • hmm, this could be a solution. [Though](https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided)... – Buddy Bob Jun 06 '21 at 20:00
0

One way this could be done and suggested by almost everyone who has commented is by using a dictionary then flipping the keys and values.

variables = {'my_variable':'my_new_variable'}
flipped = {v:k for k,v in variables.items()}

output

{'my_new_variable': 'my_variable'}
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44