Reputation: 909
I have this code which takes the a string output and converts it into a dict, it works but I wonder if there is a better way particularly with regard to splitting the string as its a bit clunky.
Code
string = "Position = 1009.82391102873, Height = 8.3161791611302, Weight = 0.650591370984836"
def string_to_dict(string):
mydict = {}
temp_list = list(string.split(","))
big_list = []
for item in temp_list:
item_split_list = list(item.split(" = "))
big_list.append(item_split_list)
mydict[item_split_list[0]] = item_split_list[1]
return mydict
mydict = string_to_dict(string)
print(mydict)
print(type(mydict))
Returns
{'Position': '1009.82391102873', ' Height': '8.3161791611302', ' Weight': '0.650591370984836'}
<class 'dict'>
Upvotes: 0
Views: 85
Reputation: 1776
Just for the beauty of the exercice, the shortest form I could think of is:
>>> eval(f"dict({string})")
{'Position': 1009.82391102873, 'Height': 8.3161791611302, 'Weight': 0.650591370984836}
or without f-strings
>>> eval("dict({})".format(string))
{'Position': 1009.82391102873, 'Height': 8.3161791611302, 'Weight': 0.650591370984836}
However, given the reading difficulty, I would not say this is the best pythonic way
Upvotes: 1
Reputation: 6234
you can use dictionary comprehension to create a new dictionary.
your_dict = {
pair.split("=")[0].strip(): pair.split("=")[1].strip()
for pair in string.split(",")
}
Upvotes: 1
Reputation: 26321
You can do it in one line:
dct = dict(s.split('=') for s in string.replace(' ', '').split(','))
But if you want the values to be float
:
dct = {k: float(v) for s in string.replace(' ', '').split(',') for k, v in [s.split('=')]}
Outcome:
>>> dct
{'Position': 1009.82391102873, 'Height': 8.3161791611302, 'Weight': 0.650591370984836}
Upvotes: 1
Reputation: 19320
A one-liner:
dict(kv.replace(" ", "").split("=") for kv in string.split(","))
which gives
{'Position': '1009.82391102873',
'Height': '8.3161791611302',
'Weight': '0.650591370984836'}
That line first splits the original string by ,
to separate the string into a list of "key = value"
. The whitespace in those strings is removed to get strings like "key=value"
, and then those strings are split by =
to get a list like [["key1", "value1"], ["key2", "value2"]]
. Because those lists are all length 2, we can pass it to dict
to construct a dictionary.
As @VishalSingh comments, this will not work if keys or values have white space.
Upvotes: 1
Reputation: 147
Concatenating could help a little bit maybe.
[input]
keys = [x.split('=')[0].strip() for x in string.split(',')]
arg = [x.split('=')[1].strip() for x in string.split(',')]
new_dict = dict(zip(keys, arg))
[output]
new_dict
{'Position ': ' 1009.82391102873',
' Height ': ' 8.3161791611302',
' Weight ': ' 0.650591370984836'}
Upvotes: 1
Reputation: 31
temp_list = list(string.split(","))
new_dict = {temp_list[i].split("=")[0].strip():temp_list[i].split("=")[1].strip()}
It's a little weird but it works and its more "pythonic"
Upvotes: 1