Names of objects in a list?
<p>I'm trying to iteratively write dictionaries to file, but am having issues creating the unique filenames for each dict.</p>

<pre><code>def variable_to_value(value):
    for n, v in globals().items():
        if v == value:
            return n
    else: 
        return None

a = {'a': [1,2,3]}
b = {'b': [4,5,6]}
c = {'c': [7,8,9]}

for obj in [a, b, c]:
    name = variable_to_value(obj)
    print(name)
</code></pre>

<p>This prints:</p>

<pre><code>a
obj
obj
</code></pre>

<p>How can I access the name of the original object itself instead of <code>obj</code>? </p>

<p>The problem is that <code>obj</code>, your iteration variable is also in <code>globals</code>. Whether you get <code>a</code> or <code>obj</code> is just by luck. You can't solve the problem in general because an object can have any number of assignments in globals. You could update your code to exclude known references, but that is very fragile.</p>

<p>For example</p>

<pre><code>a = {'a': [1,2,3]}
b = {'b': [4,5,6]}
c = {'c': [7,8,9]}

print("'obj' is also in globals")

def variable_to_value(value):
    return [n for n,v in globals().items() if v == value]

for obj in [a, b, c]:
    name = variable_to_value(obj)
    print(name)

print("you can update your code to exclude it")

def variable_to_value(value, exclude=None):
    return [n for n,v in globals().items() if v == value and n != exclude]

for obj in [a, b, c]:
    name = variable_to_value(obj, 'obj')
    print(name)

print("but you'll still see other assignments")

foo = a
bar = b
bax = c

for obj in [a, b, c]:
    name = variable_to_value(obj, 'obj')
    print(name)
</code></pre>

<p>When run</p>

<pre><code>'obj' is also in globals
['a', 'obj']
['b', 'obj']
['c', 'obj']
you can update your code to exclude it
['a']
['b']
['c']
but you'll still see other assignments
['a', 'foo']
['b', 'bar']
['c', 'bax']
</code></pre>

python list introspection