1

I have a piece of data that looks like this. How do I save it into a csv file? I was thinking of adding it to another list but I'm not sure if that will work. I tried to use the solution of the question asked in the link below, however then the csv file only saves the coordinates of the last image.

How do I write this piece of data to a csv file?

data = 
[{'box': [43, 37, 133, 168], 
 'confidence': 0.99, 
 'keypoints': {'left_eye': (78, 104), 
               'right_eye': (143, 99), 
               'nose': (110, 137), 
               'mouth_left': (82, 161), 
               'mouth_right': (147, 156)}}]

[{'box': [34, 33, 119, 161], 
  'confidence': 0.99,
  'keypoints': {'left_eye': (61, 104), 
                'right_eye': (116, 99), 
                'nose': (86, 133), 
                'mouth_left': (67, 161), 
                'mouth_right': (117, 156)}}]

It's my first time asking a question so pardon me if its not clear!

My expected output is this: sample

Ayushi
  • 33
  • 4
  • 2
    Welcome to StackOverflow. Please post the linked data directly to your question and refrain from using indirect information such as links, images ,etc. BTW, your `data` doesn't seem like a valid python object. It is supposed to be a list of lists of dict? – Chris Apr 05 '19 at 05:34
  • Yes! It is supposed to look like that. – Ayushi Apr 05 '19 at 05:39

1 Answers1

0
import csv

fields = ['box', 'confidence', 'left_eye', 'right_eye', 'nose', 'mouth_left', 'mouth_right']

with open('output.csv', 'w') as file:
    writer = csv.DictWriter(file, fieldnames=fields)
    writer.writeheader()
    for item in data:
        writer.writerow({
            'box': item['box'],
            'confidence': item['confidence'],
            'left_eye': item['keypoints']['left_eye'],
            'right_eye': item['keypoints']['right_eye'],
            'nose': item['keypoints']['nose'],
            'mouth_left': item['keypoints']['mouth_left'],
            'mouth_right': item['keypoints']['mouth_right'],
        })
John Gordon
  • 29,573
  • 7
  • 33
  • 58