I have a dictionary:
dict = [{'account': 'xyz', 'email':'[email protected]'}, {'account': 'xyz', 'email':'[email protected]'}, {'account': 'qwe', 'email':'[email protected]'}, ..., ...]
For each of the 'accounts' on the dictionary, I want to create a CSV file and the CSV file should have each of the emails belonging to the same account. So, there are multiple files for multiple accounts. For example, the CSV file xyz.csv should have:
So far, I have tried creating multiple strings (as many as the number of items the dictionary has):
for i in dict:
globals()[f'list_{i}'] = ""
and opened the files and wrote every time for each element. However, I am trying to see if I can write it to strings first and then write it to the files in a single loop. The accounts are already sorted.
Please help. **the Main objective is to open and write to the files as few times as possible. **
CodePudding user response:
Fist, don't overwrite builtins such as dict:
data = [{'account': 'xyz', 'email':'[email protected]'}, {'account': 'xyz', 'email':'[email protected]'}, {'account': 'qwe', 'email':'[email protected]'}, ..., ...]
If you don't need to keep a grouped collection of the accounts/emails you can just use a dictionary to keep each file open and linked to an email, then close the files after:
files = {}
for account, email in map(dict.values, data):
files.setdefault(account, open(f'{account}.txt', 'w')).write(f'{email},')
for file in files.values(): file.close()
Alternatively, you can use collections.defaultdict to group the emails:
from collections import defaultdict
grouped = defaultdict(list)
for account, email in map(dict.values, data):
grouped[account].append(email)
for account, emails in grouped.items():
with open(f'{account}.txt') as f:
f.writelines(f'{email},' for email in emails)
