0

I am pulling data from a csv file and have it printing out three letter country codes from each row of data. How do I make python identify the number of occurrences of each unique country code from the outputted data? Here is what I have that is printing the country codes.

import csv

with open('2017CountryData.csv') as csvfile:

  readCSV = csv.reader(csvfile, delimiter=',')
  for row in readCSV:
        countries = row[1]
        print(countries)
Austin
  • 25,759
  • 4
  • 25
  • 48
  • 1
    Take a look at the `Counter` class in the `collections` module. – Rory Daulton Jun 01 '18 at 08:13
  • 1
    Use a `Counter` [How to count the occurrences of a list item](https://stackoverflow.com/questions/2600191/how-to-count-the-occurrences-of-a-list-item/5829377#5829377). Declare `count = Counter()` above the loop, then inside the loop increment it: `count[country) += 1` – smci Jun 01 '18 at 08:15

1 Answers1

0

Use collections.Counter:

import csv

with open('2017CountryData.csv') as csvfile:
    countries = []
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        if row[1] not in countries:
            countries.append(row[1])

print(Counter(countries))
Austin
  • 25,759
  • 4
  • 25
  • 48
  • 1
    Small point, you don't *need* to convert a `Counter` object to a regular `dict` object. A `Counter` *is* a dictionary, just with some modifications / additional methods specific to counting. – jpp Jun 01 '18 at 08:18
  • 1
    @jpp thanks for your point. I doubt OP might get confuse with output of `Counter` object, so thought about converting to a regular `dict`. – Austin Jun 01 '18 at 08:20