Saturday, 24 August 2013

Getting the name of a variable as a string

Getting the name of a variable as a string

This thread discusses how to get the name of a function as a string in
Python: How to get the function name as string in Python?
How can I do the same for a variable? (note that Python variables do not
have the attribute __name__, at least in Python 2.7.x)
In other words, if I have a variable such as:
foo = dict()
foo['bar'] = 2
I am looking for a function/attribute, e.g. retrieve_name:
retrieve_name(foo)
that returns the string 'foo'
Since people are asking why I want to do this, here is an example. I would
like to create a DataFrame in Pandas from this list, where the column
names are given by the names of the actual dictionaries:
# List of dictionaries for my DataFrame
list_of_dicts = [n_jobs, users, queues, priorities]

No comments:

Post a Comment