1

In the following code, what is the _ for in the loop? Why do we use it? Is it language agnostic?

Also, what is the line

dic = {key:value for (key, value) in zip(headers, row) }

doing?

def parse_file(datafile):
    result = []
    f = open(datafile)

    # loop over the first 11 lines of a file, split() each line
    # and produce a list of stripped() values
    rows = []
    for _ in xrange(11):
        line = f.readline()
        row  = [ value.strip() for value in line.split(',') ] 
        rows.append(row)

    f.close()

    # pop() the first row from rows and use it as headers
    headers = rows.pop(0)

    for row in rows:
        # dic is a dictionary of header-value pairs for each row, 
        # produced by using the builtin zip() function
        # and the dictionary comprehension technique.
        dic = { key:value for (key, value) in zip(headers, row) }

        result.append(dic)        
    return result
Jwan622
  • 11,015
  • 21
  • 88
  • 181
  • 1
    The dupe for the other question is [Python Dictionary Comprehension](http://stackoverflow.com/q/14507591) – Bhargav Rao Dec 13 '15 at 21:05
  • The `_` is just a throw away variable name, you could use any other variable name instead. – Randrian Dec 13 '15 at 21:06
  • Since the *dictionary comprehension* part has been answered already, you should edit that part out. Or this might get flagged. – xyres Dec 13 '15 at 21:08
  • Note that if you're studying this code to learn from it, you might want to find a better model: this code is unpythonic in many ways. – DSM Dec 13 '15 at 21:12

0 Answers0