Convert strings of assignments to dicts in Python
<p>I have the following strings - they are assignment commands:</p>

<pre><code>lnodenum = 134241
d1 = 0.200000
jobname = 'hcalfzp'
</code></pre>

<p>Is there a way to convert this string, containing variables and values, to keys and values of a dictionary? It'd be equivalent to executing the below command:</p>

<pre><code>my_dict = dict(lnodenum = 134241, d1 = 0.200000, jobname = 'hcalfzp')
</code></pre>

<p>I guess this is one way to do it:</p>

<pre><code>my_str = """lnodenum = 134241
            d1 = 0.200000
            jobname = 'hcalfzp' """
exec('my_dict = dict(%s)' % ','.join(my_str.split('\n')))
</code></pre>

<p>Not sure whether anyone would think of a more concise way?</p>

<p>Note: I am using my own code for scientific computing, so I don't mind having code with safety concerns like malicious input data. But, I do prefer to have code that is shorter and easier to read :)</p>

<p>There's no need for <code>exec</code>. Just use a regular assignment with the <code>dict</code> function.</p>

<pre><code>my_str = """lnodenum = 134241
            d1 = 0.200000
            jobname = 'hcalfzp' """
my_dict = dict(pair for pair in (line.strip().split(' = ') for line in my_str.splitlines()))
</code></pre>

<p>Result:</p>

<pre><code>&gt;&gt;&gt; my_dict
{'d1': '0.200000', 'lnodenum': '134241', 'jobname': "'hcalfzp'"}
</code></pre>

<p>Or, if you'd like to parse each object, use <code>ast.literal_eval</code> with a comprehension:</p>

<pre><code>import ast
my_dict = {k:ast.literal_eval(v) for k,v in (line.strip().split(' = ') for line in my_str.splitlines())}
</code></pre>

<p>Result:</p>

<pre><code>&gt;&gt;&gt; my_dict
{'d1': 0.2, 'lnodenum': 134241, 'jobname': 'hcalfzp'}
</code></pre>

python dictionary