【问题标题】:Why do I get ValueError: dict contains fields not in fieldnames when trying to write Python dict to csv?为什么我在尝试将 Python dict 写入 csv 时收到 ValueError: dict contains fields not in fieldnames?
【发布时间】:2019-12-13 01:35:02
【问题描述】:

我收到了这个错误

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 文件,其中包含标题为“用户名”和“密码”的列,然后是这些列中的字典键和值。我玩弄了一些其他解决方案来将字典写入 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 还很陌生,因此非常感谢任何指导!我显然很难理解如何以导出到 excel 的方式访问字典项目。先感谢您。

【问题讨论】:

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


    【解决方案1】:

    这是一个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})
    

    【讨论】:

    • 您好,感谢您这么快的回复。在我的第一大块代码中,这是我编写它的方式,但导致开头提供的 ValueError。
    • 你的dictt喜欢什么?
    • print(dictt) 的输出是 {'jdoe': '$234^%$', 'sburry': '456@#&^', 'mfisc': '%6$@# ', 'nhay': 'ildfu45', 'bobama': 'klj43509jafd', 'bgates': '^&%kjsfd934@#$', 'mcuban': '9&4rl#nsf'} 和类是 'dict'跨度>
    • 和我的答案码一样试试op_writer.writerow(dictt)
    • 当你运行完整的代码时,你能用字典项创建一个成功的 csv 吗?还是您收到和我一样的错误?
    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    相关资源
    最近更新 更多