0

Hi I am trying to learn higher order functions (HOF's) in python. I understand their simple uses for reduce, map and filter. But here I need to create a tuple of the stations the bikes came and went from with the number of events at those stations as the second value. Now the commented out code is this done with normal functions (I left it as a dictionary but thats easy to convert to a tuple).

But I've been racking my brain for a while and cant get it to work using HOF's. My idea right now is to somehow use map to go through the csvReader and add to the dictionary. For some reason I cant understand what to do here. Any help understanding how to use these functions properly would be helpful.

import csv

#def stations(reader):
#    Stations = {}
#    for line in reader:
#        startstation = line['start_station_name']
#        endstation = line['end_station_name']
#        Stations[startstation] = Stations.get(startstation, 0) + 1
#        Stations[endstation] = Stations.get(endstation, 0) + 1
#    return Stations
Stations = {}
def line_list(x):
    l = x['start_station_name']
    l2 = x['end_station_name']
    Stations[l] = Stations.get(l, 0) + 1
    Stations[l2] = Stations.get(l2, 0) + 1
    return dict(l,l2)
with open('citibike.csv', 'r') as fi:
    reader = csv.DictReader(fi)
    #for line in reader:
    output = list(map(line_list,reader))
    #print(listmap)

#output1[:10]
print(output)
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

1

list(map(...)) creates a list of results, not a dictionary.

If you want to fill in a dictionary, you can use reduce(), using the dictionary as the accumulator.

from functools import reduce

def line_list(Stations, x):
    l = x['start_station_name']
    l2 = x['end_station_name']
    Stations[l] = Stations.get(l, 0) + 1
    Stations[l2] = Stations.get(l2, 0) + 1
    return Stations

with open('citibike.csv', 'r') as fi:
    reader = csv.DictReader(fi)
    result = reduce(line_list, reader, {})
print(result)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you this helped. So map can only create lists and not tuples or dicts. Now I have to see if there is a way I can squeeze the line_list down into a lambda function. Thank you – Steven Alsheimer Feb 21 '20 at 03:05
  • 1
    I don't think you can do it in a lambda, because it needs to assign to the dictionary and also return it. – Barmar Feb 21 '20 at 03:07
  • 1
    A lambda can't have multiple statements, it just returns an expression. – Barmar Feb 21 '20 at 03:08
  • Yeah I really cant figure out a nice way of doing this without dictionaries and this seems good for me right now. – Steven Alsheimer Feb 21 '20 at 03:12