skip to Main Content

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


  1. Chosen as BEST ANSWER

    Answered myself. I was able to use the eval() method to resolve this issue.

    input_string = '{"Column A": str, "Column B": str}'
    
    dict = eval(input_string)
    
    print(dict)
    

    The output is {'Column A': <class 'str'>, 'Column B': <class 'str'>}. No error.


  2. 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 the ast 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:

    import ast
    
    input_string = '{"Column A": str, "Column B": str}'
    
    # Safely evaluate the string as a Python expression
    dictionary = ast.literal_eval(input_string)
    
    print(dictionary)
    

    Output:

    {'Column A': <class 'str'>, 'Column B': <class 'str'>}
    

    Now you have a dictionary with the correct data types. You can pass this dictionary to the converters parameter of the read_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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search