简体   繁体   中英

Pythonic way of making a dict from a string

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'>

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'}
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"

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}

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.

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(",")
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM