1

如何转换字符串

s = "1:5.9,1p5:7,2:10,4:18,8:40"

像这样的字典?

s = { '1':'5.9','1p5':'7','2':'10','4':'18','8':40'}
4

1 回答 1

5

使用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'}
于 2013-08-23T13:27:43.283 回答