Retrieving a variable's name.

Evan Klitzke evan at yelp.com
Mon Aug 20 23:42:46 EDT 2007


On 8/20/07, rodrigo <rodrigo.cr at gmail.com> 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
                break
    return d

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

-- 
Evan Klitzke <evan at yelp.com>



More information about the Python-list mailing list