Retrieving a variable's name.

Evan Klitzke evan at
Tue Aug 21 05:42:46 CEST 2007

On 8/20/07, rodrigo < at> wrote:
> How would I go about retrieving a variable's name (not its value)? I
> want to write a function that, given a list of variables, returns  a
> string with each variable's name and its value, like:
> a: 100
> b: 200

Let me preface my response by saying that this is a really weird thing
to do, and almost certainly _not_ what you want to be doing.  If I was
to run across code like this, I'd be appalled ;-)  Here's one way to
do it, however:

def make_dict(*args):
    d = {}
    for arg in args:
        for key, value in globals().iteritems():
            if value is arg:
                d[key] = value
    return d

Note that this returns a dictionary, rather than a string, but this is
trivial to modify.

Evan Klitzke <evan at>

More information about the Python-list mailing list