0

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

1 Answer 1

2

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'}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your comment! The drawback of this is the integers and floats become strings, though.
Beautiful! Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.