Convert list of strings to dictionary

Solution 1:

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}

Solution 2:

Try this

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]:

Solution 3:

a = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
b = dict([i.split(': ') for i in a])
final = dict((k, int(v)) for k, v in b.items())  # or iteritems instead of items in Python 2
print(final)

Result

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

Solution 4:

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.