Using Python's csv.dictreader to search for specific key to then print its value -


background:

i having issues trying search through csv files. i've gone through python documentation: http://docs.python.org/2/library/csv.html csv.dictreader(csvfile, fieldnames=none, restkey=none, restval=none, dialect='excel', *args, **kwds) object of csv module.

my understanding csv.dictreader assumes first line/row of file fieldnames, however, csv dictionary file starts "key","value" , goes on atleast 500,000 lines.

my program ask user title (thus key) looking for, , present value (which 2nd column) screen using print function. problem how use csv.dictreader search specific key, , print value.

sample data: below example of csv file , contents...

"mamer","285713:13"  "champhol","461034:2"  "station palais","972811:0" 

so if want find "station palais" (input), output 972811:0. able manipulate string , create overall program, need csv.dictreader.i appreciate assistance.

edited part:

    import csv      def main():         open('anchor_summary2.csv', 'rb') file_data:         list_of_stuff = []         reader = csv.dictreader(file_data, ("title", "value"))             in reader:               list_of_stuff.append(i)             print list_of_stuff      main() 

the documentation linked provides half answer:

class csv.dictreader(csvfile, fieldnames=none, restkey=none, restval=none, dialect='excel', *args, **kwds)

[...] maps information read dict keys given optional fieldnames parameter. if fieldnames parameter omitted, values in first row of csvfile used fieldnames.

it seem if fieldnames parameter passed, given file not have first record interpreted headers (the parameter used instead).

# file_data text of file, not filename reader = csv.dictreader(file_data, ("title", "value")) in reader:   list_of_stuff.append(i) 

which (apparently; i've been having trouble it) produce following data structure:

[{"title": "mamer", "value": "285713:13"},  {"title": "champhol", "value": "461034:2"},  {"title": "station palais", "value": "972811:0"}] 

which may need further massaged title-to-value mapping this:

data = {} in list_of_stuff:   data[i["title"]] = i["value"] 

now use keys , values of data complete task.


and here dictionary comprehension:

data = {row["title"]: row["value"] row in csv.dictreader(file_data, ("title", "value"))} 

Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -