0

I want to do the below in python.The csv file is:

 item1,item2,item2,item3
 item2,item3,item4,item1

i want to make a dictionary with unique keys item1, item2, item3 and item4. dictionary = {item1: value1, item2: value2....}. Value is how many times the key appears in csv file.How can I do this?

kate
  • 71
  • 4
  • How are you with checking the possible duplicates before commencing a new thread?!... http://stackoverflow.com/questions/14091387/creating-a-dictionary-from-a-csv-file http://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file – User May 18 '15 at 13:51

3 Answers3

1

Obtain a list of all items from your cvs:

with open('your.csv') as csv:
    content = csv.readlines()
    items = ','.join(content).split(',')

Then start the mapping

mapping = {}
for item in items:
    mapping[item] = (mapping.get(item) or 0) + 1

and your will get the following:

>>> mapping
{'item2': 3, 'item3': 2, 'item1': 2, 'item4': 1}
bagrat
  • 7,158
  • 6
  • 29
  • 47
1
import csv
from collections import Counter

# define a generator, that will yield you field after field
# ignoring newlines:
def iter_fields(filename):
    with open(filename, 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            for field in row:
                yield field

# now use collections.Counter to count your values:
counts = Counter(iter_fields('stackoverflow.csv'))

print counts
# output:
# Counter({'item3': 2, 'item2': 2, 'item1': 1, 
# ' item1': 1, ' item2': 1, 'item4': 1})

see https://docs.python.org/2/library/collections.html#collections.Counter

m.wasowski
  • 6,329
  • 1
  • 23
  • 30
0
  import csv

  temp = dict()
  with open('stackoverflow.csv', 'rb') as f:
      reader = csv.reader(f)
      for row in reader:
          for x in row:
              if x in temp.keys():
                  temp[x] = int(temp[x]) + 1
              else:
                 temp[x] = 1
  print temp

The output is like:-

{'item2': 3, 'item3': 2, 'item1': 2, 'item4': 1}
Sheesh Mohsin
  • 1,455
  • 11
  • 28