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?
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.
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.
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.
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.
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}
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]:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With