0

I have a .csv file which looks like below:

A,3
B,2
C,5
D,1

I want to store the above values in a dictionary where an alphabet is the key. My code is below:

reader11 = csv.reader(open('file.csv'))
for row in reader11:
   if row and row[0]:
      excount[row[0]]=[i for i in row[1] if i]
print excount.items()

excount is:

[('A', ['3']), ('B', ['2']), ('C', ['5']), ('D', ['1'])]

The numbers are stored as strings in excount. How do I store them as numbers(like below)?

[('A', [3]), ('B', [2]), (C, [5]), ('D', [1])]
Karvy1
  • 959
  • 6
  • 14
  • 25
  • 1
    You should check [here](http://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file) and [here](http://stackoverflow.com/questions/14091387/creating-a-dictionary-from-a-csv-file) – Cleb Jul 19 '15 at 21:48

1 Answers1

1

You can pass a string to the built-in int() function to turn it into a number. Something like this could work:

excount[row[0]] = [int(i) for i in row[1] if i]

For more about the int function, refer to the Python documentation.

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62