committedandroider
committedandroider

Reputation: 9261

How to have the variable evaluated in dict function?

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?

Upvotes: 0

Views: 65

Answers (1)

Jonty Morris
Jonty Morris

Reputation: 807

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())

Upvotes: 2

Related Questions