Reputation: 96
I have a dictionary:
dic = {"HM1": ['Jackson','Matt','M','Football'], "SM2":['Scott','Max','M']}
i need a code that "writes" these dictionary data to csv file in the form:
HM1,Jackson,Matt,M,Football
SM2,Scott,Max,M
i have a following code which doesn't work:
with open("file.csv", "w", newline="") as new_data:
fieldnames = ['ID','Firstname','Lastname','Gender','Sports']
data_writer = csv.DictWriter(new_data, fieldnames=fieldnames)
for k in dic.keys():
r = dic[k]
data_writer.writerow({'ID':r[0],'Firstname':r[1],'Lastname':r[2],'Gender':r[3],'Sports':r[4]})
Upvotes: 0
Views: 83
Reputation: 13888
Corrected code:
with open("file.csv", "w", newline="") as new_data:
fieldnames = ['ID','Firstname','Lastname','Gender','Sports']
data_writer = csv.DictWriter(new_data, fieldnames=fieldnames)
data_writer.writeheader()
for k,r in dic.items():
data_writer.writerow({fieldnames[i]: k if i == 0 else r[i-1] for i in range(len(r)+1)})
Some issues from your original code:
1.) You never wrote the "ID" column from the dictionary key.
2.) You could easily iterate over dic.items()
which returns both key and item instead of using r = dic[k]
.
3.) Your r
is returning an IndexError
because your second row is missing a value, so r[4]
will raise an error with a list length of only 3. This could be easily handled dynamically with a list comprehension instead.
Anyhow, the output:
ID,Firstname,Lastname,Gender,Sports HM1,Jackson,Matt,M,Football SM2,Scott,Max,M,
I would recommend you handle the missing data from the lists somehow (like 'N/A') instead of just leaving the lists in uneven length. The other answer's pandas
solution is great, but if you are not comfortable with that module or installing external modules in general, this solution sticks with csv
only.
Upvotes: 0
Reputation: 6386
first, make sure that your list have the same length,
if so you have to convert it to a dataframe and convert the dataframe to a csv file by using pandas module: inatall it by using
pip install pandas
and import it like this :
import pandas as pd
df = pd.DataFrame({"HM1": ['Jackson','Matt','M','Football'], "SM2":['Scott','Max','M', '']})
df = df.T
df.to_csv('path_to_file.csv', header=False)
UPDATE : if your data lists doesn't have the same length you can proceded like this :
data_dict= {"HM1": ['Jackson','Matt','M','Football'], "SM2":['Scott','Max','M']}
df = pd.DataFrame(data=[x for x in data_dict.values()], index= data_dict.keys())
df.fillna('', inplace=True)
df.to_csv('path_to_file.csv', header=False)
Upvotes: 1