-3

I have a simple function to parse a .csv as follows

def grabber3(datafile):

with open(datafile, 'rb') as f:
    r =csv.DictReader(f)
    for line in r:
        del line['thisthing']
        print line

This print out each dict line correctly which is about 50 lines such as

{'NetworkStatus': '1', 'ID': '1469'}
{'NetworkStatus': '1', 'ID': '1470'}
etc etc

However I i want to return this when the function is called so I change the print statement to return as

def grabber3(datafile):

with open(datafile, 'rb') as f:
    r =csv.DictReader(f)
    for line in r:
        del line['thisthing']
    return line

but it only returns the first line

{'NetworkStatus': '1', 'ID': '1469'}

How do I return each line of the loop/all of the dict lines instead of just the first one?

shaktimaan
  • 11,962
  • 2
  • 29
  • 33
Jay
  • 496
  • 1
  • 4
  • 11
  • first, you need to fix your tabs. the only way that's happening is if `return ` is part of the `for line...` block. – acushner Aug 26 '14 at 19:46
  • Correct the indentation in you function definitions to make it readable and understandable. It seems that in your second function definition you should append lines to some list and return a list of dictionaries. – Radosław Roszkowiak Aug 26 '14 at 19:46
  • or, what you really want, is a map of `ID` to `NetworkStatus` – acushner Aug 26 '14 at 19:48
  • In your current edit, the code would return the last line and not the first. I think your `del` and `return` are the same indentation level when you observe the first line being returned. – shaktimaan Aug 26 '14 at 19:50
  • fixed indent to make more sense in question – Jay Aug 26 '14 at 19:55

1 Answers1

7

An efficient way of doing this is to use yield:

def grabber3(datafile):
    with open(datafile, 'rb') as f:
        r =csv.DictReader(f)
        for line in r:
            del line['thisthing']
            yield line

And then in the code that calls this function, you can do:

dict_generator = grabber3(a_file)

And then iterate through this dict_generator as:

for a_dict in dict_generator:
    print a_dict

More on yield and generators here:

  1. https://wiki.python.org/moin/Generators
  2. What does the "yield" keyword do in Python?
Community
  • 1
  • 1
shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • This worked just as I needed .Thanks. been away from python world awhile. Did not realize yield – Jay Aug 26 '14 at 19:54