How to have the variable evaluated in dict function?

Question:

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?

Asked By: committedandroider

||

Answers:

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())
Answered By: Jonty Morris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.