如何转换字符串
s = "1:5.9,1p5:7,2:10,4:18,8:40"
像这样的字典?
s = { '1':'5.9','1p5':'7','2':'10','4':'18','8':40'}
如何转换字符串
s = "1:5.9,1p5:7,2:10,4:18,8:40"
像这样的字典?
s = { '1':'5.9','1p5':'7','2':'10','4':'18','8':40'}
使用dict()
和str.split
:
>>> s = "1:5.9,1p5:7,2:10,4:18,8:40"
>>> dict(item.split(':') for item in s.split(','))
{'1': '5.9', '8': '40', '2': '10', '4': '18', '1p5': '7'}
使用字典理解:
>>> {k:v for k, v in (item.split(':') for item in s.split(','))}
{'1': '5.9', '8': '40', '2': '10', '4': '18', '1p5': '7'}