HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModerate

Convert data into dictionary

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertintodatadictionary

Problem

I am trying to convert "Random = 1" into dictionary {"Random":1}
I tried

Key = (line.split('=')[0]).split()[0] #to get key and remove spaces
value = (line.split('=')[1]).split()[0]
CQ_Options[Key] = value


How could I do it in more mature way?

Solution

First off, you should standardize your names, Key and value don't follow the same naming rules, or if they do, they're not apparent to me.
And so I'd recommend that you name your things in lower_snake_case, to adhere to PEP8.

After this I'd use str.strip rather than str.split.
And use a list comprehension to change both the key and value without having to duplicate the code, which can remove the key and value variables altogether.
This can leave you with:

item = [i.strip() for i in line.split('=')]
CQ_options[item[0]] = item[1]


If you want to stick with using key and value however, you need to make sure that line.split('=') will only return two items. You can make sure it'll return a max of two items with the optional parameter, and since we'd already error if there's not at least a single =, then you can use:

key, value = [i.strip() for i in line.split('=', 1)]
CQ_options[key] = value

Code Snippets

item = [i.strip() for i in line.split('=')]
CQ_options[item[0]] = item[1]
key, value = [i.strip() for i in line.split('=', 1)]
CQ_options[key] = value

Context

StackExchange Code Review Q#160297, answer score: 10

Revisions (0)

No revisions yet.