
How to Clean Your Cutting Board
Q: How to convert a string to a list in a dictionary in python So I'm working with Google Sheets and python. And I want to pull data from a cell and add it to a dictionary as a list. So I get a cell's content and it's just a string but I want to convert it to a list and append that to a dictionary
Here is what the cell content looks like:
"['1/5/2022 8:00:00', 8, 'Name']"
Here is what I currently have:
sheet = wks.get_all_records()
dateTime = sheet[0]['Date']
print(sheet[0]['Date'])
>> "['1/5/2022 8:00:00', 8, 'Name']"
I want to get:
["1/5/2022 8:00:00", 8, "Name"]
Is there any built-in python function that can do this? or is there any way to do this with the json module? Thanks
A: You can use the ast.literal_eval to do this.
In [1]: x = "['1/5/2022 8:00:00', 8, 'Name']"
In [2]: import ast
In [3]: ast.literal_eval(x)
Out[3]: ['1/5/2022 8:00:00', 8, 'Name']
Note that if you are not sure if every item in the dict has a parsable value like this, you can write a function to help:
def maybe_literal_eval(x):
if isinstance(x, str):
try:
return ast.literal_eval(x)
except ValueError:
return x
return x
Then apply it to every value in the dict:
{k: maybe_literal_eval(v) for k, v in sheet.items()}