Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 208
VeilEclipse Avatar asked Apr 10 '14 07:04

VeilEclipse


People also ask

Can you turn a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can you turn a string into a dictionary?

To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function. Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.

Can a list be a key in a dictionary Python?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.

Can a list be a value in a dictionary Python?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.


2 Answers

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}
like image 125
Michel Keijzers Avatar answered Oct 05 '22 02:10

Michel Keijzers


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]:
like image 30
Nishant Nawarkhede Avatar answered Oct 05 '22 02:10

Nishant Nawarkhede