Python - 没有逗号的打印字典

时间:2016-11-05 19:37:32

标签: python dictionary

我正在处理音乐API并将结果写入文件,如下所示:

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 to file
      with io.open('db/json' + '/' + user + '_' + product + '_' + filter_name + '.json', 'a', encoding='utf-8') as f:
           f.write(json.dumps(data, ensure_ascii=False, indent=4, sort_keys=True))

数据打印如下:

}{
    "artist": "Radiohead", 
    "feature": "tempo", 
    "track": "Climbing Up the Walls", 
    "value": 78.653
}{
    "artist": "The Verve", 
    "feature": "tempo", 
    "track": "The Drugs Don't Work", 
    "value": 77.368
}{

瓶颈在于,在代码的下方,我尝试使用eval评估此文件,并生成错误:

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

如何插入此'逗号分隔词典?

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试编写JSON数据。如果是这种情况,您可以使用json模块将字典转储到文件中。您应该首先将所有数据对象附加到单个music列表中。然后,您可以将该列表编码为JSON并将其写入文件。

import json

music = [
    {
        "artist": "Radiohead", 
        "feature": "tempo", 
        "track": "Climbing Up the Walls", 
        "value": 78.653
    },
    {
        "artist": "The Verve", 
        "feature": "tempo", 
        "track": "The Drugs Don't Work", 
        "value": 77.368
    }
]

with open('music.json') as f:
    json.dump(music, f, sort_keys=True, indent=4)

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

此外,如果您能提供帮助,则不应使用eval();特别是从文件中读取随机输入时。它非常脆弱(正如你已经发现的那样),但它也非常不安全。有人可以轻松地将恶意代码放入您正在评估的文件中。

相反,您应该使用json.load()从文件加载JSON。这将确保文件格式正确的JSON,并为您完成所有繁重的任务。

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