为什么在尝试将Python dict写入csv时出现ValueError:dict包含字段名称中未包含的字段?

时间:2019-12-13 01:35:02

标签: python python-3.x csv dictionary export-to-csv

我收到此错误

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

具有以下代码:

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()

该项目的目的是与继承和子类一起创建一个csv文件,该文件包含标题为“ Username”和“ Password”的列,然后分别包含这些列中的字典键和值。我想出了一些其他解决方案,可以将字典写到csv中,然后将其发布,但是导致空白csv文件仅包含标题或其他类型的错误。例如:

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

            op_writer.writeheader()

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

我收到此错误:

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

我对Python相当陌生,因此任何指导将不胜感激!我显然很难理解如何以导出为ex​​cel的方式访问字典项。先感谢您。

1 个答案:

答案 0 :(得分:0)

这是DictWriter,仅接收dict 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})