Skip to content

Instantly share code, notes, and snippets.

@radupotop
Created July 22, 2024 09:55
Show Gist options
  • Save radupotop/da5878bef58f7efe9b88a318cd78e78b to your computer and use it in GitHub Desktop.
Save radupotop/da5878bef58f7efe9b88a318cd78e78b to your computer and use it in GitHub Desktop.
import csv
import sys
def print_dict_as_csv(dict_data):
if not dict_data:
print("The dictionary is empty.")
return
# Get the fieldnames from the keys of the first dictionary
fieldnames = dict_data[0].keys()
# Create a CSV writer object that writes to sys.stdout
csvwriter = csv.DictWriter(sys.stdout, fieldnames=fieldnames)
# Write the header
csvwriter.writeheader()
# Write the rows
for row in dict_data:
csvwriter.writerow(row)
# Example usage
data = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Los Angeles"},
{"name": "Charlie", "age": 35, "city": "Chicago"}
]
print_dict_as_csv(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment