My code works even though I didn't put the dictionary key / fieldnames in the CSV file

35 views Asked by At
import csv

phone = input("Enter phone name")
os = input("Enter OS")

with open("phos.csv", "a") as phos:
    phos_dict = csv.DictWriter(phos, fieldnames = ["phone_model", "phone_os"])
    phos_dict.writerow({"phone_model": phone, "phone_os": os})

The above code works just fine even though I left the CSV file empty. Then how does the code know how to implement/write the dictionary to the phos.csv file properly?

1

There are 1 answers

3
Luis Felipe On

It works because you set the fieldnames. Then, when you send the dict with the correct keys, the code knows where to put the values.

If you pass a key:value in phos_dict.writerow({"phone_model": phone, "phone_os": os}) that was not implemenet in fieldnames = ["phone_model", "phone_os"] you'll get the following error:

ValueError: dict contains fields not in fieldnames