0

For example I have 2 variables:

a = 2 + 2
b = 3 + 3

And now I want to construct a dictionary where keys are variable names, that is “a”, “b” and values are 4 and 6 accordingly.


{x: x for x in (a, b)}
# --→  {4: 4, 6: 6}

Question is that I don't know how to make keys “a” and “b” instead of 4 and 6. str(), str doesn't work. Each time x as a key gets evaluated and becames 4 or 6

Desirable output would be

{a: 4, b: 6}

Thank you!

Aleksei Khatkevich
  • 1,923
  • 2
  • 10
  • 27
  • What are you trying to do this for? – Sayse Jun 14 '19 at 09:49
  • You could just use `locals()` but there really isn't any need to do this – Sayse Jun 14 '19 at 09:50
  • Why don't you directly use ``{'a': 2+2, 'b': 3+3}``? – MisterMiyagi Jun 14 '19 at 09:51
  • This is to add into template evaluative dictionary for cache invalidation. Variables there are variables and dict values are datetime objects. Number or variables migth be 20 easily and each variable migt hold queriset of 4 rows of code, so that instead of mannualy constructin dict like {"a": a, "b":b} etc for 20 items i would rather use dict comprehension. Thats the reason, nothing fancy – Aleksei Khatkevich Jun 14 '19 at 09:52
  • I have tried use locals() as well but it works the same way. Valuables gets evaluated... – Aleksei Khatkevich Jun 14 '19 at 09:56

0 Answers0