【问题标题】:Convert a special string format into dict? [closed]将特殊的字符串格式转换为dict? [关闭]
【发布时间】:2017-12-25 01:58:39
【问题描述】:
我想转成这样的字符串:
'word1-3,word2-4,word3-1,word4-2'
进入这样的字典:
{'word1': 3 , 'word2': 4 , 'word3' : 1 , 'word4' : 2}
我该怎么做?
【问题讨论】:
-
您好,Kosar,欢迎来到 StackOveflow。请熟悉How to Ask 的指南。通常,您想提供证据证明您已经做了某事来尝试自己解决这个问题。被认为是“给我codez”类型的问题将很难收到。
标签:
python
string
python-3.x
dictionary
【解决方案1】:
如果 "-" 和 "," 字符仅用作分隔符,那么您可以尝试如下操作:
s = 'word1-3,word2-4,word3-1,word4-2'
d = dict(item.split('-') for item in s.split(','))
print(d) # >> {'word4': '2', 'word1': '3', 'word3': '1', 'word2': '4'}
或者使用字典理解并将值转换为整数:
s = 'word1-3,word2-4,word3-1,word4-2'
d = {pair[0]:int(pair[1]) for pair in [item.split('-') for item in s.split(',')]}
print(d) # >> {'word4': '2', 'word1': '3', 'word3': '1', 'word2': '4'}
【解决方案2】:
我猜你的意思是如何用代码来实现这一点,因为在大多数情况下,python 字符串无法实现这一点。
#import split from the re library
from re import split
#your example string
some_string = 'word1-3,word2-4,word3-1,word4-2'
#this will hold our values while we iterate through it
output_dict = {}
#split the some_string into a list of key value strings
for key_val_pair in split(r',', some_string):
#split the key value pair into a key and value
key_val_split = split(r'\-', key_val_pair)
#append the value to the dict, indexed by the key
output_dict[key_val_split[0]] = key_val_split[1]
output_dict 将按要求提供。