Created
July 22, 2024 09:55
-
-
Save radupotop/da5878bef58f7efe9b88a318cd78e78b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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