0

Is there any way in Python to build a dict from variable name/value to key/value without assigning explicitly?

def my_func(var1, var2):
  my_dict = dict(var1 , var2)
  print(my_dict)

my_func("x", "y")

Prints:

{"var1": "x", "var2": "y"}

Edited in order to make it less artificial. The idea is to avoid dict(var1=var1)

  • 1
    The example is artificial, why not build the dict directly without first creating the variables `var1` and `var2`? – Chris_Rands Jun 23 '20 at 08:23
  • You're asking how to make a dictionary with specified keys and values? Well, `my_dict = {'var1': var1, 'var2': var2}`. Unless I'm missing something...? – alani Jun 23 '20 at 08:27
  • not sure if that what you meant but you could do `dict(var1=var1, var2=var2)` – AvielNiego Jun 23 '20 at 08:27
  • But in one form or another, you are going to have to specify `'var1'` and `'var2'` explicitly as string constants. Where you write `var1`, this means: the object to which the name `var1` refers. That object itself contains no concept of any variable name to which it might be assigned, and indeed the same object can be assigned to multiple variables. – alani Jun 23 '20 at 08:30
  • also consider using kwargs – Kenny Ostrom Jun 24 '20 at 15:22

2 Answers2

3
var1 = "x"
var2 = "y"

my_dict = dict(var1=var1, var2=var2)

print(my_dict)

Prints:

{'var1': 'x', 'var2': 'y'}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

You can get them from the locals() dict

var1 = "x"
var2 = "y"
my_dict  = {k: v for k, v in locals().items() if k in ['var1','var2']}
print(my_dict)

Output

{'var1': 'x', 'var2': 'y'}
Leo Arad
  • 4,452
  • 2
  • 6
  • 17