Simpler way to create dictionary of separate variables? Simpler way to create dictionary of separate variables? python python

Simpler way to create dictionary of separate variables?


As unwind said, this isn't really something you do in Python - variables are actually name mappings to objects.

However, here's one way to try and do it:

 >>> a = 1 >>> for k, v in list(locals().iteritems()):         if v is a:             a_as_str = k >>> a_as_str a >>> type(a_as_str) 'str'


I've wanted to do this quite a lot. This hack is very similar to rlotun's suggestion, but it's a one-liner, which is important to me:

blah = 1blah_name = [ k for k,v in locals().iteritems() if v is blah][0]

Python 3+

blah = 1blah_name = [ k for k,v in locals().items() if v is blah][0]


Are you trying to do this?

dict( (name,eval(name)) for name in ['some','list','of','vars'] )

Example

>>> some= 1>>> list= 2>>> of= 3>>> vars= 4>>> dict( (name,eval(name)) for name in ['some','list','of','vars'] ){'list': 2, 'some': 1, 'vars': 4, 'of': 3}