How could I convert this formatted string into a key, value dictionary form?

Viewed 177

I am not pretty sure how to convert a formatted string into a dictionary, what I was thinking was to separate my string into two lists and then join them into a dictionary but I am convinced that there must be a way to convert it from string to dictionary directly.

This is what I get so far:

string:

'Me_of_temp_max: 13.91 Me_of_temp_min: 11.33 Me_of_p_max: 14.25 Me_of_p_min: 14.53'

What I am looking fro is this:

{'Me_of_temp_max': 13.91, 'Me_of_temp_min': 11.33, 'Me_of_p_max': 14.25, 'Me_of_p_min': 14.53}

But What I did to reach this was:

items = {}


result = ['Me_of_temp_max', 'Me_of_temp_min', 'Me_of_p_ma', 'Me_of_p_min']
result1 = [13.91, 11.33, 14.25, 14.53]
for i in range(len(result)):
        items[result[i]] = result1[i]
return items
5 Answers

A simple two liner using split and replace to process the string, and zip to build the dictionary :

>>> t = s.replace(':','').split()
>>> dict( zip(t[::2], list(map(float,t[1::2]))) )

#driver values :

IN : s = 'Me_of_temp_max: 13.91 Me_of_temp_min: 11.33 Me_of_p_max: 14.25 Me_of_p_min: 14.53'
OUT : {'Me_of_temp_max': 13.91, 'Me_of_temp_min': 11.33, 'Me_of_p_max': 14.25, 'Me_of_p_min': 14.53}

Further explanation :

  1. the replace function is used to remove all ':' in the strings as they are not required.
  2. the split function with space as delimiter gives us the list with key and values.
  3. the zip function creates the key-value pair for the dict
    • and since the keys are in the even positions, we get required list by using extended slicing as [::2].
    • and since the values are in the odd positions, we get required list by using extended slicing as [1::2]. And since the values should be float we use map to get list containing float values.
  4. finally type-cast it to dict .

You'd want to split on (space) and then iterate over those values.

s = 'Me_of_temp_max: 13.91 Me_of_temp_min: 11.33 Me_of_p_max: 14.25 Me_of_p_min: 14.53'

s_key_vals = s.replace(':', '').split(' ')

res = {}
for idx, key in enumerate(s_key_vals):
    if idx % 2 == 0: # will be an even number, every time ``idx`` is even, it means key is a value like: ``Me_of_temp_min`` or ``Me_of_p_min`` etc
        res[key] = float(s_key_vals[idx+1])  # Convert the number to a float instead of being left with a string.

Returns: {'Me_of_temp_min': 11.33, 'Me_of_p_min': 14.53, 'Me_of_temp_max': 13.91, 'Me_of_p_max': 14.25}

How about this:

input = "Me_of_temp_max: 13.91 Me_of_temp_min: 11.33 Me_of_p_max: 14.25 Me_of_p_min: 14.53"

spl = input.split("Me") 
spl_noempty = [("Me"+x).strip().split(':') for x in spl if x != ''] 

dic = dict(spl_noempty)
print(dic)

I split at Me, remove whitespaces. I prepend Me again and split each part at : to form a list of tuples, then dict them.

Here is a way to do it with a regular expression, which means you may need to change it to suit the exact format of your data.

import re

s = 'Me_of_temp_max: 13.91 Me_of_temp_min: 11.33 Me_of_p_max: 14.25 Me_of_p_min: 14.53'
regex = re.compile('(\w+):\s(\d+\.\d+)')
{k: float(v) for k, v in regex.findall(s)}

Output :

{'Me_of_p_max': 14.25,
 'Me_of_p_min': 14.53,
 'Me_of_temp_max': 13.91,
 'Me_of_temp_min': 11.33}

You can use `string.split(' ')' and latter take care of ':'. In this way you have a list where even and odd places contain the key and the number (as a string).

Related