Search code examples
pythonpython-3.xcsvdictionaryexport-to-csv

Why do I get ValueError: dict contains fields not in fieldnames when trying to write Python dict to csv?


I am getting this error

ValueError: dict contains fields not in fieldnames: 'bobama', 'mfisc', 'nhay', 'bgates', 'jdoe', 'sburry', 'mcuban'

with the following code:

class Authentication:
    def __init__(self):
        # instantiate an instance variable
        self.user_dict = {}

    def register_user(self, uname, passwd):
        if uname in self.user_dict:
            print("Username exists! Try a new one.")
            return False
        else:
            self.user_dict[uname] = passwd
            print("Registration successful" )
            return True    

def data_entry(auth):

    # registering 3 users
    auth.register_user('jdoe', '$234^%$') # Jane Doe
    auth.register_user('sburry', '456@#&^') # Sam Burry
    auth.register_user('mfisc', '%6&#$@#') # Mike Fischer
    auth.register_user('nhay', 'ildfu45') # Nicky Hailey
    auth.register_user('bobama', 'klj43509jafd') # Barack Obama
    auth.register_user('bgates', '^&%kjsfd934@#$') # Bill Gates 
    auth.register_user('mcuban', '9&4rl#nsf') # Mark Cuban

# Main program
auth = Authentication()
data_entry(auth)

dictt = auth.user_dict

import csv

class AuthenticationIOcsv(Authentication):
    def write_info(self):
        fname='userinfo.csv'        
        with open(fname,'w') as op_file:

            field_names = ['Username', 'Password']

            op_writer = csv.DictWriter(op_file, fieldnames=field_names)

            op_writer.writeheader()

            op_writer.writerow(dictt)        

# Main Program
auth = AuthenticationIOcsv()
data_entry(auth)

# writing to file
auth.write_info()

The aim of this project is to work with inheritance and a child class to create a csv file containing columns with the headers 'Username' and 'Password' and then the dictionary keys and values within those columns respectively. I've toyed around with a couple of other solutions to writing the dictionary to csv which I can post but have resulted in either blank csv files with just the headers or other types of errors. For example:

            op_writer = csv.DictWriter(op_file, fieldnames=field_names)

            op_writer.writeheader()

            for key, value in dictt.items():
                op_writer.writerow([key,value])

I get this error:

AttributeError: 'list' object has no attribute 'keys'

I am fairly new to Python so any guidance would be greatly appreciated! I'm clearly struggling to understand how to access the dictionary items in such a way to export to excel. Thank you in advance.


Solution

  • This is a DictWriter, only receive dict data. You can use this way to write data:

    op_writer = csv.DictWriter(op_file, fieldnames=field_names)
    op_writer.writeheader()
    for username, pwd in dictt.items():
        op_writer.writerow({"Username": username, "Password": pwd})