我怎么能将这个格式化的字符串转换为键值字典表单?

时间:2017-11-12 11:21:38

标签: python string dictionary

我不太确定如何将格式化的字符串转换为字典,我想的是将我的字符串分成两个列表,然后将它们加入字典中,但我确信必须有一种方法来转换它从字符串直接到字典。

这是我到目前为止所得到的:

的字符串:

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

我正在寻找的是:

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

但我做到的是:

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 个答案:

答案 0 :(得分:2)

使用splitreplace处理字符串的简单双线程,以及zip构建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}

进一步解释:

  1. replace函数用于删除字符串中的所有':',因为它们不是必需的。
  2. split函数以空格作为分隔符为我们提供了包含键和值的列表。
  3. zip函数为key-value创建dict
    • 由于keys位于偶数位置,因此我们使用extended slicing作为[::2]获取所需列表。
    • 由于values位于奇数位置,我们使用extended slicing作为[1::2]获取所需列表。由于值应该是 float ,我们使用map来获取包含浮点值的列表。
  4. 最后type-castdict

答案 1 :(得分:0)

您希望拆分(space),然后迭代这些值。

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.

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

答案 2 :(得分:0)

这个怎么样:

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)

我在Me拆分,删除空格。我再次添加Me并将每个部分拆分为:以形成元组列表,然后dict

答案 3 :(得分:0)

以下是使用正则表达式执行此操作的方法,这意味着您可能需要更改它以适合数据的确切格式。

{{1}}

输出:

{{1}}

答案 4 :(得分:-1)

您可以使用`string.split('')',后者可以使用':'。通过这种方式,您可以获得一个列表,其中偶数和奇数位置包含键和数字(作为字符串)。