I have a string with format:
["('colA':'datA1', 'colB':'datB1', 'colC':'datC1')",
"('colA':'datA2', 'colB':'datB2', 'colC':'datC2')",
..........
"('colA':'datAn', 'colB':'datBn', 'colC':'datCn')]
And i need to obtain a dict:
[{'colA': 'datA1', 'colB': 'datB1', 'colC': 'datC1'},
{'colA': 'datA2', 'colB': 'datB2', 'colC': 'datC2'},
..........
{'colA': 'datAn', 'colB': 'datBn', 'colC': 'datCn'}]
If possible I need to do it with Python's own functions or at least without using loops, but I do not know if this is possible.
Replace the parentheses with curly braces and use ast.literal_eval
:
import ast
l = ["('colA':'datA1', 'colB':'datB1', 'colC':'datC1')",
"('colA':'datA2', 'colB':'datB2', 'colC':'datC2')",
"('colA':'datAn', 'colB':'datBn', 'colC':'datCn')"]
result = [ast.literal_eval('{%s}' % item[1:-1]) for item in l]
The result:
>>> import pprint
>>> pprint.pprint(result)
[{'colA': 'datA1', 'colB': 'datB1', 'colC': 'datC1'},
{'colA': 'datA2', 'colB': 'datB2', 'colC': 'datC2'},
{'colA': 'datAn', 'colB': 'datBn', 'colC': 'datCn'}]
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