How to export dictionary as CSV using Python?

2024/9/20 13:35:20

I am having problems exporting certain items in a dictionary to CSV. I can export 'name' but not 'images' (the image URL).

This is an example of part of my dictionary:

new = [{ "name" : "peter", "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F33500665%2F25911657759%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C581%2C6000%2C3000&s=bfaa2901b8c906a66c51563d15c6df12"},
{"name" : "jim" , "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F32935536%2F10115879927%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C40%2C624%2C312&s=c67e995e83234ab460707ac21f3541f8"}]

EDIT (I made a mistake with the naming as was what pointed out. It seems to work now after updating it).

And this is the code I have written (which works for 'name' but not 'picture'):

import csvtest = []for document in new:event_obj = {}# Get nameevent_obj['name'] = document['name']# Get imagesevent_obj['picture'] = document['picture']test.append(event_obj)# Create CSV file
with open('Eventbrite_events.csv', 'w', newline='') as csvfile:fields = ['name', 'picture']writer = csv.DictWriter(csvfile, fieldnames=fields)writer.writeheader()for x in test:writer.writerow(x)
print(csvfile)
Answer

Your new list contains dictionaries with the key picture but you were trying to access one called images.

import csvnew = [{ "name" : "peter", "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F33500665%2F25911657759%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C581%2C6000%2C3000&s=bfaa2901b8c906a66c51563d15c6df12"},{"name" : "jim" , "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F32935536%2F10115879927%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C40%2C624%2C312&s=c67e995e83234ab460707ac21f3541f8"}]test = []for document in new:event_obj = {}# Get nameevent_obj['name'] = document['name']# Get imagesevent_obj['images'] = document['picture']test.append(event_obj)# Create CSV file
with open('Eventbrite_events.csv', 'w', newline='') as csvfile:fields = ['name', 'images']writer = csv.DictWriter(csvfile, fieldnames=fields)writer.writeheader()writer.writerows(test)

You could also make use of writerows() to write all the rows in one go.

This would give you a CSV file as follows:

name,images
peter,https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F33500665%2F25911657759%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C581%2C6000%2C3000&s=bfaa2901b8c906a66c51563d15c6df12
jim,https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F32935536%2F10115879927%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C40%2C624%2C312&s=c67e995e83234ab460707ac21f3541f8

You could also avoid building test as follows as an alternative way to rename your entry:

import csvnew = [{"name" : "peter", "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F33500665%2F25911657759%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C581%2C6000%2C3000&s=bfaa2901b8c906a66c51563d15c6df12"},{"name" : "jim" , "picture" : "https://img.evbuc.com/https%3A%2F%2Fcdn.evbuc.com%2Fimages%2F32935536%2F10115879927%2F1%2Foriginal.jpg?h=200&w=450&rect=0%2C40%2C624%2C312&s=c67e995e83234ab460707ac21f3541f8"}]# Create CSV file
with open('Eventbrite_events.csv', 'w', newline='') as csvfile:fields = ['name', 'images']writer = csv.DictWriter(csvfile, fieldnames=fields)writer.writeheader()for row in new:row['images'] = row.pop('picture')writer.writerow(row)
https://en.xdnf.cn/q/119487.html

Related Q&A

Passing values to a function from within a function in python

I need to pass values from one function to the next from within the function.For example (my IRC bot programmed to respond to commands in the channel):def check_perms(nick,chan,cmd):sql = "SELECT …

How to make Stop button to terminate start function already running in Tkinter (Python)

I am making a GUI using Tkinter with two main buttons: "Start" and "Stop". Could you, please, advise on how to make the "Stop" button to terminate the already running func…

adding language to markdown codeblock in bulk

My Problem is to add to every single block of code a language in my markdown files. Ive hundreds of files in nested directories. The files have this form: ```language a ```Normal text``` b ```Normal te…

Cant randomize list with classes inside of it Python 2.7.4

I am new to coding and I need some help. Im trying to randomize these rooms or scenes in a text adventure but whenever I try to randomize it they dont even show up when I run it! Here is the script:fro…

calculate the queue for orders based on creation and delivery date, by product group

I have a Pandas dataframe containing records for a lot of orders, one recorde for each order. Each record has order_id, category_id, created_at and picked_at. I need to calculate queue length for each …

Python print with string invalid syntax

I have a rock, paper, scissors code Ive been working on lately (yes, I am a total noob at coding), and I get an Invalid Syntax error with this specific line:print(The magical 8ball reads "Your for…

How to load images and text labels for CNN regression from different folders

I have two folders, X_train and Y_train. X_train is images, Y_train is vector and .txt files. I try to train CNN for regression. I could not figure out how to take data and train the network. When i us…

How to calculate number of dates within a year of a date in pandas

I have the following dataframe and I need to calculate the amount of ER visit Dates with a score of 1 that are one year after the PheneDate for that pheneDate for a given subject. So basically phenevi…

Remove substring from string if substring in list in data frame column

I have the following data frame df1string lists 0 i have a dog [fox, dog, cat] 1 there is a cat [dog, house, car] 2 hello everyone [hi, hello, everyone] 3 …

how to save data in the db django model?

Good day, I cant really understand what Im doing wrong in here. I was using this function base view to store my scrap data in the database with the django model, but now its not saving any more. I cant…