Convert list of strings to dictionary

前端 未结 7 933
深忆病人
深忆病人 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条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 22:30

    Loop over your list, and split by the colon. Then assign the first value to the second value in a dict object:

    x = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
    y = {}
    for k in x:
        c = k.split(':')
        y[str(c[0]).replace(" ", "")] = str(c[-1]).replace(" ", "")
    
    print(y)
    #{'Failures': '0', 'Tests run': '1', 'Errors': '0'}
    

提交回复
热议问题