-1

I am trying to execute below code but it's throwing some error, whereas same code is running on jupyter notebook. I am not sure what's going wrong. The python version is 2 on both platform. This codes takes json file as input, pick 'Data' key and place all values under it into csv file.

command line :

Python version : 2.6.6

$ python Parser.py /data/csdb/stage/fundapiresponse.json /data/csp53/csdb/stage/fundresponse.csv
  File "Parser.py", line 27
    flat_data = [{k:v for j in i for k, v in j.items()} for i in zip(*[element['Data'] for key in element])]
                        ^
SyntaxError: invalid syntax

Code:

#################################################
# importing libraries
#################################################
import csv
import json
import collections
import sys

#################################################
# Reading input and output file from command line
#################################################

infile = sys.argv[1]
outfile = sys.argv[2]

print infile
print outfile

#################################################
# Read JSON and build CSV layout
#################################################
with open(infile,'r') as f:
    data= json.load(f)

with open(outfile, 'w') as f:
    for element in data: 
        flat_data = [{k:v for j in i for k, v in j.items()} for i in zip(*[element['Data'] for key in element])]
        csvwriter = DictWriter(f,flat_data[0].keys(),lineterminator='\n')
        csvwriter.writerows(flat_data)

Jupyter notebook :

Python 2

#################################################
# importing libraries
#################################################
import csv
import json
import collections
import sys

#################################################
# Reading input and output file from command line
#################################################

infile = 'fundapiresponse.json'
outfile = 'fundresponse.csv'

print infile
print outfile

#################################################
# Read JSON and build CSV layout
#################################################
with open(infile,'r') as f:
    data= json.load(f)

with open(outfile, 'w') as f:
    for element in data: 
        flat_data = [{k:v for j in i for k, v in j.items()} for i in zip(*[element['Data'] for key in element])]
        csvwriter = DictWriter(f,flat_data[0].keys(),lineterminator='\n')
        csvwriter.writerows(flat_data)
Praveenks
  • 1,436
  • 9
  • 40
  • 79

1 Answers1

3

Dict comprehensions (PEP274) with curly brackets and colon notation were only introduced in Python2.7. Before that, you had to use the dict constructor with an appropriate list or generator of pairs:

dict((k, v) for j in i for k, v in j.iteritems())  # items works, too

See also Alternative to dict comprehension prior to Python 2.7.

Community
  • 1
  • 1
user2390182
  • 72,016
  • 6
  • 67
  • 89