简体   繁体   English

CSV 文件的字典列表

[英]List of dictionaries to CSV file

I have a list of dictionaries:我有一个字典列表:

[   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'},)]

In my situation, I need to put all this data to CSV file, so via csv module, I try to write all this data to CSV file but I receive every time error message:在我的情况下,我需要将所有这些数据放入 CSV 文件,因此通过 csv 模块,我尝试将所有这些数据写入 CSV 文件,但每次都会收到错误消息:

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

So I add to 'fieldnames' address, but the problem is that I receive all data in one column of 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)

You'll need to flatten out the structure so it's just a list of dictionaries holding strings and numbers, rather than a list of dictionaries holding dictionaries of strings and numbers.您需要将结构展平,使其只是包含字符串和数字的字典列表,而不是包含字符串和数字字典的字典列表。

Assuming that you don't want to modify this list just for the writing step, make a new empty list.假设您不想仅为写入步骤修改此列表,请创建一个新的空列表。 Copy the dictionaries from one list to the other, but convert the address dictionary into a set of additional fields called address.address_country , address.city , address.state and so on.将字典从一个列表复制到另一个列表,但将address字典转换为一组名为address.address_countryaddress.cityaddress.state等的附加字段。

Then use csv to write out this new list, and pass it the modified fieldnames.然后使用csv写出这个新列表,并将修改后的字段名传递给它。

Also don't forget to test with commas inside the field strings.另外不要忘记在字段字符串中使用逗号进行测试。

Pandas offers a convenient alternative: Pandas 提供了一个方便的替代方案:

# first flatten address
for d in lst:
    d.update(d['address'])
    del d['address']

# read into dataframe
df = pd.DataFrame(d, index=range(len(lst)))

# output to csv
df.to_csv('file.csv', index=False)

# Result
#   account_id address_country  affiliate_id brand               city country  \
# 0                         ZM            12   TTT  North Matthewland      ZM   

#                  email first_name last_name  leadsource password phone_number  \
# 0  rosariojohn@TTT.zed      Peter     Green         559  test385    052839601   

#     state         street_name  street_number zip_code  
# 0  Nevada  Cabrera Extensions            197    81431 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM