将词典另存为CSV



我想更改这个字典:

{'GB00011785': ['The Shipyard, Bath Rd, Lymington SO41 3YL, United Kingdom'], 'GB00024511': ['17 Meadowbank Way, Eastwood, Nottingham NG16 3SB, United Kingdom', '73 Burton Rd, Withington, Manchester M20 1HB, United Kingdom']}

收件人:注意有两个地址的重复GB00024511

{'GB00011785': ['The Shipyard, Bath Rd, Lymington SO41 3YL, United Kingdom'], 'GB00024511': ['17 Meadowbank Way, Eastwood, Nottingham NG16 3SB, United Kingdom'],['GB00024511':'73 Burton Rd, Withington, Manchester M20 1HB, United Kingdom']}

然后我想导出到CSV,看起来像这样:

Registration_Number   Address
GB00011785            'The Shipyard, Bath Rd, Lymington SO41 3YL, United Kingdom'
GB00024511            '17 Meadowbank Way, Eastwood, Nottingham NG16 3SB, United Kingdom'
GB00024511            '73 Burton Rd, Withington, Manchester M20 1HB, United Kingdom'

有人知道我会怎么做吗?

目前我的代码生成这个文件:

GB00024511                                                   GB00011785 
['The Shipyard, Bath Rd, Lymington SO41 3YL, United Kingdom']  ['17 Meadowbank Way, Eastwood, Nottingham NG16 3SB, United Kingdom', '73 Burton Rd, Withington, Manchester M20 1HB, United Kingdom']

这是代码:

import csv
with open('AddressesFound.csv', 'w') as f:
w = csv.DictWriter(f,dictionary.keys())
w.writerow(dictionary)

以下可能会有所帮助:

d1={'GB00011785': ['The Shipyard, Bath Rd, Lymington SO41 3YL, United Kingdom'], 'GB00024511': ['17 Meadowbank Way, Eastwood, Nottingham NG16 3SB, United Kingdom', '73 Burton Rd, Withington, Manchester M20 1HB, United Kingdom']}

转换为Pandas数据帧:

df1 = pd.DataFrame.from_dict(d1, orient='index')

保存为csv:

df1.to_csv('df1.csv', index=False)

要获得所需格式的DataFrame:

df2 = df1.stack().to_frame().reset_index(drop=False)
df2.columns = ['Registration', 'l1', 'Addresses']
df2.to_csv('df2.csv', index=False) 

字典不能有重复的键。此外,如果要使用csv.DictWriter,则希望每行都是一个字典,将字段名称映射到该行的值。

你可以首先使用列表理解来转换你的原始dict:

source = {'GB00011785': ['The Shipyard, Bath Rd, Lymington SO41 3YL, United Kingdom'],
'GB00024511': ['17 Meadowbank Way, Eastwood, Nottingham NG16 3SB, United Kingdom', '73 Burton Rd, Withington, Manchester M20 1HB, United Kingdom']}
csv_rows = [{'Registration_Number': key, 'Address': addr} 
for key, value in source.items() 
for addr in value]

产生这种结构的:

[{'Registration_Number': 'GB00011785', 'Address': 'The Shipyard, Bath Rd, Lymington SO41 3YL, United Kingdom'}, 
{'Registration_Number': 'GB00024511', 'Address': '17 Meadowbank Way, Eastwood, Nottingham NG16 3SB, United Kingdom'}, 
{'Registration_Number': 'GB00024511', 'Address': '73 Burton Rd, Withington, Manchester M20 1HB, United Kingdom'}]

然后,您可以写出与您尝试的方式相当相似的行:

import csv
with open('AddressesFound.csv', 'w') as f:
writer = csv.DictWriter(f, ('Registration_Number', 'Address'))
writer.writeheader()
writer.writerows(csv_rows)

最新更新