-2

I have a CSV file, having two columns: "id" and "quantity". The file has a header with the two columns mentioned (id and quantity), and from the second row on the values.

For ex, the file would look like this:

id, quantity
1234,100
2345,200
3456,300
4567,400

I want to create a Python dict from the csv, which reads the CSV above in a dictionary, so that I can then later easily check if a specific id is in the dictionary, and if it is there, what is the value (quantity).

Anyone knows how to do that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ZelelB
  • 1,836
  • 7
  • 45
  • 71

1 Answers1

1

Yes, just use the built-in csv module:

import csv
import itertools

with open('data.csv') as f:
    reader = csv.reader(f)
    next(reader) # skip the header
    stream = ((int(x), int(y)) for x,y in reader)
    my_dict = dict(stream)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • Thanks! And if the columns aren't int, would that work too? Like strings or dates? And how to check if an id is in the dict? If yes, what is its quantity? – ZelelB Dec 27 '19 at 19:40