I have a string dictionary as user input in Python console.
The string format looks like "{"Column A": str, "Column B": str}"
. Eventually, I want to convert this string to dict format like {"Column A": str, "Column B": str}
so that I could use it in Pandas read_csv() converters.
However, I was unable to use json.loads() to convert, since the values are not string, but data types. I’m wondering if there’s any good way to convert this string into dictionary?
2
Answers
Answered myself. I was able to use the eval() method to resolve this issue.
The output is
{'Column A': <class 'str'>, 'Column B': <class 'str'>}
. No error.If I understand correctly, you have a string representation of a dictionary where the values are not string literals but actual data types. In this case, you can use the
ast.literal_eval()
function from theast
module in Python to safely evaluate the string as a Python expression. Here’s an example of how you can use it to convert your string to a dictionary:Output:
Now you have a dictionary with the correct data types. You can pass this dictionary to the
converters
parameter of theread_csv()
function in pandas to define custom converters for specific columns.Keep in mind that
ast.literal_eval()
evaluates the string as a Python expression, so make sure the input string is trusted and doesn’t contain any malicious code.