Tuesday, 6 August 2013

From string in a csv cell to dict

From string in a csv cell to dict

I have a CSV with a column named availableexits. Its data is thus :
'N=1,E=4,S=7'
I want to put it in a dict so it looks like :
d = {'N':1, 'E':4, 'S':7}
(stop there if you have an answer, below just shows how I do it now)
Currently I read the column data as a string :
'N=1,E=4,S=7'
then I split it on commas g = d.split(",")
g = ['S=1', 'W=3', 'N=4']
then i split each of those on the =
h = []
for x in g :
h.append(x.split("="))
#h is now [['N', '1'], ['E', '3'], ['S', '4']]
and then cast as a dict
e = dict(h) #looks very German
#e is now {'S': '1', 'W': '3', 'N': '4'}
I just cast the value to an int when I use it.
I have a feeling I am a horrible person for doing it this way. Whats a
better way.

No comments:

Post a Comment