I'm just beginning at Python and stackoverflow, forgive me for any mis开发者_StackOverflow中文版takes...
I'm trying to use dictreader and dictwriter for a project of mine. Basically I have a dictionary of songs, which contains many keys (names, artists, play count, song tags for example).
The problem is that when I feed dictwriter into a file, it takes every key and applies the type string to the value.
This isn't a problem for playcount where I can just say int(), but for song tags I have a list of tuples which displays the tag with the amount of times tagged For example: [(Rock, 50), (Roll, 50)].
Now when I read this out of my file, row["tags"] has type string... I don't know how to get it to have the appropriate type.
My sort've silly solution which I haven't tried yet is to search through the string for a (, then a ), and append that to a new list, then do it until I've iterated throughout the tags... But it seems like there should be an easier way...
If your CSV consists of the representation of basic Python types then you can use ast.literal_eval()
to convert it to Python types.
精彩评论