I understand the very basics of programming in python and here is my problem. I have following json file from the developer API for League of Legends (a video game) (excerpt):
"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.
My code:
#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)
What I have done so far:
- I was able to load the file in my program
- I created custom headers in a csv file
- I am able to print the data for a specific "keys" (ex: Aatrox)
- I can also print the "stats" of a specific "keys"
What I would like to do now:
- Create a line in a CSV-file for each "keys" with the "stats"-value separated by commas
I believe that I will be able to create a loop that goes through all the keys by myself. However I fail to find easy to understand information on how to write the dictionary to a CSV-file in my desired format. Could anyone help me out with this. What I am most interested in understanding is:
- How do I write a dictionary-value to a string with a specific format?
- How can I tell python to put the dictionary-value under the correct header, which I have specified?