Python代码将字典输出写入csv文件

时间:2020-01-02 14:09:09

标签: python csv

我有Json格式的输出

{ 
   'name':'Ellemeet',
   'id':'10019',
   'nametype':'Valid',
   'recclass':'Diogenite',
   'mass':'1470',
   'fall':'Fell',
   'year':'1925-01-01T00:00:00.000',
   'reclat':'51.750000',
   'reclong':'4.000000',
   'geolocation':{ 
      'latitude':'51.75',
      'longitude':'4.0'
   },
   'distance':84.00378375664592
}

我正在使用下面的代码将此行写入CSV文件

for meteor in meteor_data:
    ...:     print(meteor)
    ...:     if not ('reclat' in meteor and 'reclong' in meteor): continue
    ...:     meteor['distance'] = calc_dist(float(meteor['reclat']), float(meteor['reclong']), \
    ...:     my_loc[0], my_loc[1])
    ...:     with open('names1.csv', 'w') as csvfile:
    ...:         writer = csv.writer(csvfile)
    ...:         for name, id, nametype, recclass, mass, fall, year, reclat, reclong, geolocation, distance \
    ...:         in meteor.items().split(','):
    ...:             writer.writerow([name, id, nametype, recclass, mass, fall, year, reclat, \
    ...:             reclong, geolocation, distance])

在运行代码时,我遇到了值错误异常

ValueError:没有足够的值可解包(预期11,得到2)

1 个答案:

答案 0 :(得分:0)

这个我的朋友正是熊猫库的构建对象。请花一些时间来学习它pandas

现在您的问题。

import pandas as pd
df = pd.DataFrame.from_dict(meteor_data)
df.to_csv('test.csv')

应该为您做。