Python Copy dictionary

41 Views Asked by At

I am trying to copy the dictionary structure so I can create multple list. error

Traceback (most recent call last):
File "C:/data/LEARNING/PHYTON/excel/Exercise/pywrite2", line 22, in \<module\>
csv_reader1 = dict.copy(csv_reader)
TypeError: descriptor 'copy' for 'dict' objects doesn't apply to a '\_csv.reader' object

Code

import csv
import copy
count1=0

with open('C:\\data\\LEARNING\\PHYTON\\excel\\MySQL\\texperts\\supplier.csv','r') as csv_data:
     csv_reader =csv.reader(csv_data, delimiter=',')
     csv_reader1 = dict.copy(csv_reader)
        csv_reader1.append(row1)

print(category)
print(countlist)
csv_data.close()

I have read and tried different variation of the copy.copy, dict.copy. It seem the "import copy" is greyed out at the top. I read that the copy is already installed, but when i review my pycharm setting, I don't see the copy package.

2

There are 2 best solutions below

0
Krishna Gunjan On
import csv
with open('C:\data\LEARNING\PHYTON\excel\MySQL\texperts\supplier.csv', 'r') as csv_data:
     csv_reader = csv.reader(csv_data, delimiter=',')
     csv_data_list = list(csv_reader) 
     csv_data_list_copy = csv_data_list.copy() 
0
codeR On

As specified in the documentation, csv.reader returns a 'reader object' which is not exactly a dictionary map. Instead, you can use csv.DictReader which returns a dict map.

following snippet is adapted from the official documentation page

import csv
with open('your_file.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=',') # DictReader object
    for row in reader: # each row is a dict object
        print(row)