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>Python doesn't actually work like this.</p>

<p>Objects in Python don't have innate names. It's the names that belong to an object, not the other way around: an object can have many names (or no names at all).</p>

<p>You're getting two copies of "obj" printed, because at the time you call <code>variable_to_value</code>, both the name <code>b</code> and the name <code>obj</code> refer to the same object! (The dictionary <code>{'b': [4,5,6]}</code>) So when you search for the global namespace for any value which is equal to <code>obj</code> (note that you should be checking using <code>is</code> rather than <code>==</code>) it's effectively random whether or not you get <code>b</code> or <code>obj</code>.</p>

python list introspection