将字符串列表转换为字典 [英] Convert list of strings to dictionary

查看:211
本文介绍了将字符串列表转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单

['Tests run: 1', ' Failures: 0', ' Errors: 0']

我想将其转换为字典

{'Tests run': 1, 'Failures': 0, 'Errors': 0}

我该怎么做?

推荐答案

使用:

a = ['Tests run: 1', ' Failures: 0', ' Errors: 0']

d = {}
for b in a:
    i = b.split(': ')
    d[i[0]] = i[1]

print d

返回:

{' Failures': '0', 'Tests run': '1', ' Errors': '0'}

如果需要整数,请在以下位置更改赋值:

If you want integers, change the assignment in:

d[i[0]] = int(i[1])

这将给出:

{' Failures': 0, 'Tests run': 1, ' Errors': 0}

这篇关于将字符串列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆