1

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)

6
  • 1
    The example is artificial, why not build the dict directly without first creating the variables var1 and var2? Commented Jun 23, 2020 at 8: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...? Commented Jun 23, 2020 at 8:27
  • not sure if that what you meant but you could do dict(var1=var1, var2=var2) Commented Jun 23, 2020 at 8: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. Commented Jun 23, 2020 at 8:30
  • also consider using kwargs Commented Jun 24, 2020 at 15:22

2 Answers 2

3
var1 = "x"
var2 = "y"

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

print(my_dict)

Prints:

{'var1': 'x', 'var2': 'y'}
Sign up to request clarification or add additional context in comments.

1 Comment

My idea is to do perform this without assigning var1=var1 @andrej-kesely
1

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'}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.