Yuxiang Wang Yuxiang Wang - 1 month ago 7
Python Question

Convert strings of assignments to dicts in Python

I have the following strings - they are assignment commands:

lnodenum = 134241
d1 = 0.200000
jobname = 'hcalfzp'


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:

my_dict = dict(lnodenum = 134241, d1 = 0.200000, jobname = 'hcalfzp')


I guess this is one way to do it:

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


Not sure whether anyone would think of a more concise way?

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 :)

Answer

There's no need for exec. Just use a regular assignment with the dict function.

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()))

Result:

>>> my_dict
{'d1': '0.200000', 'lnodenum': '134241', 'jobname': "'hcalfzp'"}

Or, if you'd like to parse each object, use ast.literal_eval with a comprehension:

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

Result:

>>> my_dict
{'d1': 0.2, 'lnodenum': 134241, 'jobname': 'hcalfzp'}
Comments