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?
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:valueinphos_dict.writerow({"phone_model": phone, "phone_os": os})that was not implemenet infieldnames = ["phone_model", "phone_os"]you'll get the following error:ValueError: dict contains fields not in fieldnames