0

Below is the code to convert csv file to json format in python. I have two fields 'recommendation' and 'rating'. Based on the recommendation value I need to set the value for rating field like if recommendation is 1 then rating =1 and vice versa. With the answer I got I'm getting output for only one record entry instead of getting all the records. I think it's overriding. Do I need to create separate list for that and append each record entry to the list to get the output for all records. here's the updated code:

def main(input_file):
csv_rows = []
with open(input_file, 'r') as csvfile:
    reader = csv.DictReader(csvfile, delimiter='|')
    title = reader.fieldnames
    for row in reader:
        entry = OrderedDict()
        for field in title:
            entry[field] = row[field]
        [c.update({'RATING': c['RECOMMENDATIONS']}) for c in reader]
        csv_rows.append(entry)

with open(json_file, 'w') as f:
    json.dump(csv_rows, f, sort_keys=True, indent=4, ensure_ascii=False)
    f.write('\n')

I want to create the nested format like the below:

"rating": {
"user_rating": {
  "rating": 1
},
"recommended": {
  "rating": 1
}

1 Answer 1

0

After you've read the file in, using the csv.DictReader, you'll have a list of dicts. Since you want to set the values now, it's a simple dict manipulation. There are several ways, of which one is:

[c.update({'rating': c['recommendation']}) for c in read_csvDictReader]

Hope that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

with the above code I'm getting only one record values in the output instead of all records. Do I need to store the above code result into some variable and use it?
update modifies in place. I'd like to see what's in read_csvDictReader, if you don't mind

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.