Home > Net >  How to have the variable evaluated in dict function?
How to have the variable evaluated in dict function?

Time:10-04

This is what I have

TEST_KEY = "test_key"

def get_dict():
   return dict(TEST_KEY = "test_value")

print(get_dict())

This will print out {'TEST_KEY': 'test_value'}

but I want it evaluate to {'test_key': 'test_value'}

Is there a way to achieve this, to have python not evaluate TEST_KEY inside the dict function as a literal String but instead as the variable defined earlier?

CodePudding user response:

Very close! But the way you're assigning the key and value is not quite right.

Try changing dict to {} and = to : like below. This will use the variable value as the key.

TEST_KEY = "test_key"

def get_dict():
   return {TEST_KEY: "test_value"}

print(get_dict())
  • Related