python - CSV 文件的词典列表

标签 python csv dictionary

我有一个字典列表:

[   defaultdict(<class 'dict'>,
                {   'account_id': '',
                    'address': {   'address_country': 'ZM',
                                   'city': 'North Matthewland',
                                   'state': 'Nevada',
                                   'street_name': 'Cabrera Extensions',
                                   'street_number': 197,
                                   'zip_code': '81431'},
                    'affiliate_id': 12,
                    'brand': 'TTT',
                    'country': 'ZM',
                    'email': 'rosariojohn@TTT.zed',
                    'first_name': 'Peter',
                    'last_name': 'Green',
                    'leadsource': 559,
                    'password': 'test385',
                    'phone_number': '052839601'},)]

在我的情况下,我需要将所有这些数据放入 CSV 文件,因此通过 csv 模块,我尝试将所有这些数据写入 CSV 文件,但每次都会收到 错误消息:

ValueError: dict contains fields not in fieldnames: 'address' 

所以我添加到“fieldnames”地址,但问题是我在一列地址中收到所有数据。

with open('test_file.csv', 'w') as csvfile:
    filed_names = ['first_name',
                   'last_name',
                   'email',
                   'phone_number',
                   'password',
                   'country',
                   'leadsource',
                   'affiliate_id',
                   'account_id',
                   'brand',
                   'street_number',
                   'street_name',
                   'city',
                   'state',
                   'address_country',
                   'zip_code',
                   ]
    writer = csv.DictWriter(csvfile, fieldnames=filed_names)
    writer.writeheader()
    writer.writerows(list_user_details)

最佳答案

您需要展平结构,使其只是包含字符串和数字的字典列表,而不是包含字符串和数字的字典的字典列表。

假设您不想仅为了写入步骤而修改此列表,请创建一个新的空列表。将字典从一个列表复制到另一个列表,但将 address 字典转换为一组名为 address.address_countryaddress.city 的附加字段、address.state 等等。

然后使用 csv 写出这个新列表,并将修改后的字段名称传递给它。

另外,不要忘记在字段字符串内使用逗号进行测试。

关于python - CSV 文件的词典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49111440/

相关文章:

python - Keras 均方误差损失层

python - Django Auth,登录问题

python - 如何管理 argparse 中的优先级?

python - 将 csv 转换为 netcdf

r - 自定义名称从数据表包 R 下载 csv

mysql - 将csv数据导入Mysql数据库

python - 将 MultiIndex Pandas DataFrame 添加到 PyTables HDFStore 的问题

python - 基于Python中的键聚合字典列表上的值

python - 使用短路运算符编辑字典

c++ - 为什么我不能用一对作为键来编译 unordered_map?