Sometimes, we want to create dictionary of separate variables with Python.
In this article, we’ll look at how to create dictionary of separate variables with Python.
How to create dictionary of separate variables with Python?
To create dictionary of separate variables with Python, we can get the local variables in a dict with locals
.
For instance, we write
blah = 1
blah_name = [k for k, v in locals().items() if v is blah][0]
to get an iterator of tuples of the local variables with
k for k, v in locals().items()
Then we get the one from the iterator that has value blah
with
if v is blah
And then we use index 0 to get the first entry that matches the condition.
Conclusion
To create dictionary of separate variables with Python, we can get the local variables in a dict with locals
.