dictionary - Python - printing dictionaries without commas -


i procesing music apiand writing results file, so:

for val, track_id in zip(values,list(track_ids)):     #below     if val < threshold:        data = {"artist": sp.track(track_id)['artists'][0]['name'], "track":sp.track(track_id)['name'], "feature": filter_name, "value": val}       #write file       io.open('db/json' + '/' + user + '_' + product + '_' + filter_name + '.json', 'a', encoding='utf-8') f:            f.write(json.dumps(data, ensure_ascii=false, indent=4, sort_keys=true)) 

data printed follows:

}{     "artist": "radiohead",      "feature": "tempo",      "track": "climbing walls",      "value": 78.653 }{     "artist": "the verve",      "feature": "tempo",      "track": "the drugs don't work",      "value": 77.368 }{ 

the bottleneck that, further down code, try evaluate file eval, , generates error:

  file "<string>", line 6     }{      ^ 

how insert 'comma separate dicionaries?

it looks you're trying write json data. if that's case can dump dictionary file using json module. should first append data objects single music list. can encode list json , write file.

import json  music = [     {         "artist": "radiohead",          "feature": "tempo",          "track": "climbing walls",          "value": 78.653     },     {         "artist": "the verve",          "feature": "tempo",          "track": "the drugs don't work",          "value": 77.368     } ]  open('music.json') f:     json.dump(music, f, sort_keys=true, indent=4) 

https://docs.python.org/2/library/json.html#json.dump

additionally, should not using eval() if can it; when reading random input file. it's incredibly fragile (as you've discovered) it's incredibly insecure. put malicious code file you're evaluating.

instead, should use json.load() load json file. ensure file formatted json , heavy lifting you.

with open('music.json') f:     music = json.load(f) 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -