Reputation: 785
I have a csv file that I've turned into a list()
so that I can iterate over it to do some simple transformations with the data, however when I try to get the output I only get the key for each of the items (when what I need are the values).
The code I'm using right now is as follows (slightly truncated for clarity):
lines = list(csvdataFishes)
while (startTime + 30) > timeToEpoch(currLine['timestamp']) >= startTime:
cx = someFunction1()
uf = someFunction2()
rf = someFunction3()
pc = someFunction4()
outline = [k for k in lines[i] if k is not ''] + [cx,uf,rf,pc]
print ','.join(outline)
i += 1
currLine = lines[i]
startTime = startTime + 30
If I do a simple print lines[i]
I get something like:
{
'adjusted timestamp': '2014-08-23 17:20:05.43000',
'fishType': 'small green fish',
'playerID': '3',
'timestamp': '2014-08-23 16:21:05.430000-05:00',
'targetID': '34',
'lights': '1',
'event': 'MakeSpawnFish'
}
but the output of print ','.join(outline)
just gives me the keys for the [k for k in lines[i] if k is not '']
and the correct output for [cx,uf,rf,pc]
(like so):
adjusted timestamp,fishType,playerID,timestamp,targetID,lights,event,1,1,2,1
What I'm wondering is how I get it to give the values (and not the key) for the [k for k in lines[i] if k is not '']
Upvotes: 2
Views: 73
Reputation: 1765
Lines is a list of dicts. If you iterate over a dict, you get its keys. To get the values instead, use dict.values()
. So you need to change this line:
outline = [k for k in lines[i] if k is not ''] + [cx,uf,rf,pc]
to
outline = [k for k in lines[i].values() if k is not ''] + [cx,uf,rf,pc]
Upvotes: 2
Reputation: 4155
You can use the keys
and values
builtins:
>>> [k for k in lines[i].keys() if k is not '']
['fishType', 'timestamp', 'event', 'targetID', 'playerID', 'lights', 'adjusted timestamp']
and
>>> [k for k in lines[i].values() if k is not '']
['small green fish', '2014-08-23 16:21:05.430000-05:00', 'MakeSpawnFish', '34', '3', '1', '2014-08-23 17:20:05.43000']
These will iterate over the dictionary's keys and values. Check out the dictionary documentation here.
Upvotes: 4
Reputation: 26667
Do you mean
[ lines[k] for k in lines if k is not '']
Test
>>> lines = {
... 'adjusted timestamp': '2014-08-23 17:20:05.43000',
... 'fishType': 'small green fish',
... 'playerID': '3',
... 'timestamp': '2014-08-23 16:21:05.430000-05:00',
... 'targetID': '34',
... 'lights': '1',
... 'event': 'MakeSpawnFish'
... }
>>> ",".join( [ lines[k] for k in lines if k is not ''] + ["1", "1", "2", "1"])
'2014-08-23 17:20:05.43000,small green fish,3,2014-08-23 16:21:05.430000-05:00,34,1,MakeSpawnFish,1,1,2,1'
Upvotes: 0