python - How to read lines of dictionary and write to a CSV file -


i have data file, format this

{"name":"david","age":"14","score":[0,1]} {"name":"jason","age":"12","score":[0,0]} 

my question : 1) how read file , convert csv

name,age,score david,14,0/1 jason,12,0 

2) how convert [0,1] 0/1, [0,0] 0, means when denominator zero, result 0, otherwise, take 1st number divide 2nd number inside []

thanks!!

for start data appears json encoded, can use json module read list of dictionaries:

import json  open('input') f:     dicts = [json.loads(line) line in f] 

for sample data dicts set to:

>>> pprint import pprint >>> pprint(dicts) [{u'age': u'14', u'name': u'david', u'score': [0, 1]},  {u'age': u'12', u'name': u'jason', u'score': [0, 0]}] 

update scores (assuming want perform division):

for d in dicts:     score = d['score']     d['score'] = score[0]/score[1] if score[1] != 0 else 0     #d['score'] = '{}/{}'.format(score[0], score[1]) if score[1] != 0 else '0' 

(the above line generate textual version of division operation, if wanted)

next can use csv.dictwriter object write output csv file.

import csv  open('output', 'w') f:     writer = csv.dictwriter(f, fieldnames=['age', 'name', 'score'])     writer.writeheader()     writer.writerows(dicts) 

finally, output file should contain:

 age,name,score 14,david,0 12,jason,0 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -