20

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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
VeilEclipse
  • 2,766
  • 9
  • 35
  • 53

7 Answers7

14

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}
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
7

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]:
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
4
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}
Georgy
  • 12,464
  • 7
  • 65
  • 73
Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
2

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.

Retozi
  • 7,521
  • 1
  • 23
  • 16
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}
Georgy
  • 12,464
  • 7
  • 65
  • 73
Bruno Gelb
  • 5,322
  • 8
  • 35
  • 50
1

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'}
Georgy
  • 12,464
  • 7
  • 65
  • 73
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
1
>>> s = ['Tests run: 1', ' Failures: 0', ' Errors: 0']
>>> {i.split(":")[0].strip():int(i.split(":")[1].strip()) for i in s}
{' Failures': 0, 'Tests run': 1, ' Errors': 0}
alvas
  • 115,346
  • 109
  • 446
  • 738