2

I have csv file with three headers( A, B and C) , I read this file as dictionary . Where the headers are Keys in the dictionary , and rows are the keys values.

I need to iterate over the dictionary values row by row, and perform some action then move to the next row(..the first loop output should be as below , without printing the index) :

Expected output in the first loop:

A:324087rwer
B:mobile
C:test

Current Code:

import csv

with open("test.csv") as f:
    rows = csv.DictReader(f)
    for row in rows:
         for key, value in enumerate(row.items()):  
            print(key, value)     

Current Output:

0 ('A', '324087rwer')
1 ('B', 'mobile ')
2 ('C', 'take ')
0 ('A', 'fweo8yr30w8yr')
1 ('B', 'keep')
2 ('C', 'remove')
0 ('A', 'erwes')
1 ('B', 'website')
2 ('C', 'blacklist')

Note : I don't want the index to be printed .

Many thanks

Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117

1 Answers1

1

The enumerate function is returning an iterator containing the loop count plus another tuple containing the dictionary key, value pairs.

This could be described with a type hint such as:

Tuple[int, Tuple[KT, VT]]

Hence, in the inner for-loop, the key variable is being assigned to the loop count and the value variable is being assigned the tuple (Tuple[KT, VT]).

If you do not need the loop counter, then you could write:

import csv

with open("test.csv") as f:
    rows = csv.DictReader(f)
    for row in rows:
         for key, value in row.items():  
            print(key, value) 

If you need the loop counter, then the following would work:

import csv

with open("test.csv") as f:
    rows = csv.DictReader(f)
    for row in rows:
        for count, (key, value) in enumerate(rows.items()):  
            print(key, value) 
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117