Vei*_*pse 8 python dictionary list python-2.7
我有一份清单
['Tests run: 1', ' Failures: 0', ' Errors: 0']
Run Code Online (Sandbox Code Playgroud)
我想将它转换为字典
{'Tests run': 1, 'Failures': 0, 'Errors': 0}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
使用:
a = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
d = {}
for b in a:
i = b.split(': ')
d[i[0]] = i[1]
print d
Run Code Online (Sandbox Code Playgroud)
收益:
{' Failures': '0', 'Tests run': '1', ' Errors': '0'}
Run Code Online (Sandbox Code Playgroud)
如果需要整数,请更改以下内容中的赋值:
d[i[0]] = int(i[1])
Run Code Online (Sandbox Code Playgroud)
这将给出:
{' Failures': 0, 'Tests run': 1, ' Errors': 0}
Run Code Online (Sandbox Code Playgroud)
尝试这个
In [35]: a = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
In [36]: {i.split(':')[0]: int(i.split(':')[1]) for i in a}
Out[36]: {'Tests run': 1, ' Failures': 0, ' Errors': 0}
In [37]:
Run Code Online (Sandbox Code Playgroud)