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 function returns the first name it finds referencing an object in your <code>globals()</code>. However, at each iteration, the name <code>obj</code> will reference each of the objects. So either the name <code>a</code>, <code>b</code> or <code>c</code> is returned or <code>obj</code>, depending on the one which was reached first in <code>globals()</code>.</p>

<p>You can avoid returning <code>obj</code> by excluding that name from the search in your function - <em>sort of hackish</em>:</p>

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

python list introspection