Convert list of strings to dictionary

前端 未结 7 871
深忆病人
深忆病人 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:15

    naive solution assuming you have a clean dataset:

    intconv = lambda x: (x[0], int(x[1]))
    
    dict(intconv(i.split(': ')) for i in your_list)
    

    This assumes that you do not have duplicates and you don't have other colons in there.

    What happens is that you first split the strings into a tuple of two values. You do this here with a generator expression. You can pass this directly into the dict, since a dict knows how to handle an iterable yielding tuples of length 2.

提交回复
热议问题