Convert list of strings to dictionary

前端 未结 7 934
深忆病人
深忆病人 2020-12-01 22:08

I have a list

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

I would like to convert it to a dictionary as

{\'Tests r         


        
7条回答
  •  旧时难觅i
    2020-12-01 22:20

    Use:

    a = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
    
    d = {}
    for b in a:
        i = b.split(': ')
        d[i[0]] = i[1]
    
    print d
    

    returns:

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

    If you want integers, change the assignment in:

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

    This will give:

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

提交回复
热议问题