Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of strings to list of dictionaries in python?

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.

like image 624
Juan Antonio Clavero Garcia Avatar asked Nov 26 '16 20:11

Juan Antonio Clavero Garcia


1 Answers

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'}]
like image 173
TigerhawkT3 Avatar answered Nov 14 '22 23:11

TigerhawkT3