我理解python编程的基础知识,这是我的问题。我有关于英雄联盟(视频游戏)的开发者API的json文件(摘录):
"keys": {
"35": "Shaco",
"36": "DrMundo",
"33": "Rammus",
AND SO ON..
},
"data": {
"Aatrox": {
"tags": [
"Fighter",
"Tank"
],
"stats": {
"attackrange": 150,
"mpperlevel": 45,
"mp": 105.6,
"attackdamage": 60.376,
AND SO ON...
},
AND SO ON.
我的代码:
#import dependencies
#to understand json
import json
#to write csv file
import csv
#to output json in a readable way in the command line
from pprint import pprint
#create the output file
outfile_path='output.csv'
#open up the file and tell the programm to write in it
writer = csv.writer(open(outfile_path, 'w'))
#Create custom headers for the data
headers =['armor', 'armorperlevel', 'attackdamage','attackdamageperlevel','attackrange', 'attackspeedoffset', 'attackspeedperlevel', 'crit', 'critperlevel', 'hp', 'hpperlevel', 'hpregen', 'hpregenperlevel', 'movespeed', 'mp', 'mpperlevel', 'mpregen', 'mpregenperlevel', 'spellblock', 'spellblockperlevel']
writer.writerow(headers)
#open data file, in order to manipulate it
with open('data.json') as data_file:
data = json.load(data_file)
#print stats for the keys Aatrox
aatrox = data['data']['Aatrox']['stats']
pprint(aatrox)
到目前为止我做了什么:
我现在想做什么:
我相信我能够自己创建一个遍历所有键的循环。但是,我找不到有关如何以我想要的格式将字典写入CSV文件的易于理解的信息。 任何人都可以帮我解决这个问题。我最感兴趣的是:
答案 0 :(得分:1)
您可以使用csv.DictWriter
:
import csv
stats = {
"attackrange": 150,
"mpperlevel": 45,
"mp": 105.6,
"attackdamage": 60.376,}
headers =['attackdamage','attackrange', 'mp', 'mpperlevel']
with open('output.csv', 'wb') as f:
writer = csv.DictWriter(
f, headers, delimiter=',', lineterminator='\n', )
writer.writeheader()
writer.writerow(stats)
生成output.csv
:
attackdamage,attackrange,mp,mpperlevel
60.376,150,105.6,45