Skip to content

Instantly share code, notes, and snippets.

@juanarrivillaga
Last active April 2, 2024 21:46
Show Gist options
  • Save juanarrivillaga/b3ae481e896c4a5dafdc582de8365550 to your computer and use it in GitHub Desktop.
Save juanarrivillaga/b3ae481e896c4a5dafdc582de8365550 to your computer and use it in GitHub Desktop.
# So, assuming the lists have the same length, e.g.:
dummy_data = {
"Date":["01/24/2029","10/28/2027", "01/24/2024","03/24/2024"],
"Company Name":["Mcdonalds", "Burger King", "KFC","Popeyes"],
"File_name_location":["C/Documents/Files/invoice1.pdf", "C/Documents/Files/invoice1.pdf","C/Documents/Files/invoice1.pdf", "C/Documents/Files/invoice1.pdf"],
}
# Then, to sort everything, simply get a list of sorted indices.
# This can be done easily. Since you don't want `datetime.date` objects
# (for some reason - you *should* probably just use them and then when you want a string simply use the `datetime.date`
# formatting tools to create whatever string you want).
sorted_indices = sorted(
range(len(dummy_data['Date'])),
key=lambda i: datetime.datetime.strptime(dummy_data['Date'][i], "%m/%d/%Y")
)
# Then finally, use the indices to re-arrange the lists in the dict:
for k, vs in dummy_data.items():
dummy_data[k] = [vs[i] for i in sorted_indices]
# Which would give the following output:
"""
{'Date': ['01/24/2024', '03/24/2024', '10/28/2027', '01/24/2029'],
'Company Name': ['KFC', 'Popeyes', 'Burger King', 'Mcdonalds'],
'File_name_location': ['C/Documents/Files/invoice1.pdf',
'C/Documents/Files/invoice1.pdf',
'C/Documents/Files/invoice1.pdf',
'C/Documents/Files/invoice1.pdf']}
"""
# also, you don't need pandas just to make a csv. that's like swatting a fly with a sledgehammer
import csv
with open('output.csv', 'w', newline="") as f:
writer = csv.writer(f)
# write the header from the keys
writer.writerow(list(dummy_data))
# write the rest of the data in the lists
writer.writerows(zip(*dummy_data.values()))
@Kevsosmooth
Copy link

import csv

test_data = [{"Company Name":"ABC", "Date":"10/24/2024"},
{"Company Name":"KKA", "Date":"2/24/2024"},
{"Company Name":"DDD", "Date":"3/24/2024"},
{"Company Name":"CCC", "Date":"8/24/2024"}]

keys = test_data[0].keys()
print(keys)

with open("silvi.csv", "w", newline='') as f:
dict_writer = csv.DictWriter(f, keys)
dict_writer.writeheader()
dict_writer.writerows(test_data)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment