# Convert list of strings to dictionary

Posted on

### Question :

Convert list of strings to dictionary

I have a list

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

I would like to convert it to a dictionary as

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

How do I do it?

Use:

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

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

print d
``````

returns:

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

If you want integers, change the assignment in:

``````d[i] = int(i)
``````

This will give:

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

``````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}
``````

Try this

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

In : {i.split(':'): int(i.split(':')) for i in a}
Out: {'Tests run': 1, ' Failures': 0, ' Errors': 0}

In :
``````

naive solution assuming you have a clean dataset:

``````intconv = lambda x: (x, int(x))

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.

``````l = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
d = dict([map(str.strip, i.split(':')) for i in l])
for key, value in d.items():
d[key] = int(value)
print(d)
``````

output:

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

``````>>> s = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
>>> {i.split(":").strip():int(i.split(":").strip()) for i in s}
{' Failures': 0, 'Tests run': 1, ' Errors': 0}
``````

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