Create dictionary where keys are variable names
<p>I quite regularly want to a dictionary where the key names are the variable names. For example if i have the variable <code>a</code> and <code>b</code> then to have a dictionary <code>{"a":a, "b":b}</code>  (typically to return data at the end of a function).</p>

<p>Is there any (ideally built in) ways in python of automatically doing this? i.e to have a function such that <code>create_dictionary(a,b)</code> returns <code>{"a":a, "b":b}</code></p>

<p>Have you considered creating a class?  A class can be viewed as a wrapper for a dictionary.  </p>

<pre><code># Generate some variables in the workspace
a = 9; b = ["hello", "world"]; c = (True, False)

# Define a new class and instantiate
class NewClass(object): pass
mydict = NewClass()

# Set attributes of the new class
mydict.a = a
mydict.b = b
mydict.c = c

# Print the dict form of the class
mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
</code></pre>

<p>Or you could use the <code>setattr</code> function if you wanted to pass a list of variable names:</p>

<pre><code>mydict = NewClass()
vars = ['a', 'b', 'c']
for v in vars: 
    setattr(mydict, v, eval(v)) 

mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
</code></pre>

python python-3.x