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>You can write your own function for <code>create_dict</code></p>

<pre><code>def create_dict(*args):
  return dict({i:eval(i) for i in args})

a = "yo"
b = 7
print (create_dict("a", "b"))
</code></pre>

<p>Which gives <code>{'a': 'yo', 'b': 7}</code> output.<br>
Here's a simple generator for the same:</p>

<pre><code>vars = ["a", "b"]
create_dict = {i:eval(i) for i in args}
</code></pre>

<p>or you can use this one-liner lambda function</p>

<pre><code>create_dict = lambda *args: {i:eval(i) for i in args}
print (create_dict("a", "b"))
</code></pre>

<p>But if you want to pass the variables to the function instead of the variable name as string, then its pretty messy to actually get the name of the variable as a string. But if thats the case then you should probably try using <code>locals()</code>, <code>vars()</code>, <code>globals()</code> as used by <a href="http://stackoverflow.com/users/6335503/nf4r">Nf4r</a> </p>

python python-3.x