问题
I'm having troubles with CSV conversion, I'm not that sure on how to do this (not that familiar with CSV conversion, testing this out as a side project) I have a nested dictionary that I want to create into a CSV:
- I want to set
STRONG_AXE
andFAST_AXE
under the columnITEM_ID
- Make another column called
base
which contains the attack values,10
and1
, same with attack speed. - Crit power has 4 parts to it, the base, scale, spread and max spread, I also want to convert all of those (this is the troublesome part for me)
into 1 column called
crit-power
with10.0 0.1 0.1 0.2
.
Let's say I have 'axe.yml' for an rpg:
# axe.yml
STRONG_AXE:
base: iron_axe
attack-damage: 10
attack-speed: 1
crit-power:
base: 10.0
scale: 0.1
spread: 0.1
maxSpread: 0.2
FAST_AXE:
base: copper_axe
attack-damage: 5
attack-speed: 2
Now I open 'axe.yml' as f (file), then I convert it into a dictionary.
#writer.py
import csv,yaml
with open(r'axe.yml') as f:
dict_data = yaml.load(f, Loader=yaml.FullLoader)
print (dict_data)
Then the convert dictionary that appears is:
{'STRONG_AXE': {'base': 'iron_axe', 'attack-damage': 10, 'attack-speed': 1, 'crit-power': {'base': 10.0, 'scale': 0.1, 'spread': 0.1, 'maxSpread': 0.2}}, 'FAST_AXE': {'base': 'copper_axe', 'attack-damage': 5, 'attack-speed': 2}}
So how would the conversion work? (Dropped coding for a while, sorry for my uh... newbie-ishness)
回答1:
Here's one way to handle the nested data. It creates separate fields for each of the items in the nested dictionary and adds a prefix to each of their names.
import csv
import yaml
from pprint import pprint
inp_filepath = 'axe.yml'
outp_filepath = 'axe.csv'
FAST, STRONG = 'FAST_AXE', 'STRONG_AXE' # Axe type ids.
COMMON_FIELDS = ['base', 'attack-damage', 'attack-speed']
STRONG_AXE_ONLY_FIELDS = ['base', 'scale', 'spread', 'maxSpread']
CRIT_POWER_FIELDS = [('crit-power-' + fieldname) for fieldname in STRONG_AXE_ONLY_FIELDS]
CSV_FILE_FIELDS = ['axe-type'] + COMMON_FIELDS + CRIT_POWER_FIELDS
with open(inp_filepath) as file:
data = yaml.load(file, Loader=yaml.FullLoader)
with open(outp_filepath, 'w', newline='') as file:
writer = csv.DictWriter(file, CSV_FILE_FIELDS)
writer.writeheader()
for axetype, axedata in data.items():
row = {'axe-type': axetype}
if axetype == FAST:
# Add common fields.
row.update({fieldname: axedata[fieldname] for fieldname in COMMON_FIELDS})
elif axetype == STRONG:
# Add common fields.
row.update({fieldname: axedata[fieldname] for fieldname in COMMON_FIELDS})
# Then add renamed STRONG only fields.
crit_power_data = axedata['crit-power']
row.update({('crit-power-' + fieldname): crit_power_data[fieldname]
for fieldname in STRONG_AXE_ONLY_FIELDS})
else:
raise RuntimeError(f'unknown axe type "{axetype}" encountered')
# pprint(row, sort_dicts=False) # Show row data being written to file.
writer.writerow(row)
print('Conversion completed')
来源:https://stackoverflow.com/questions/64946826/csv-conversion-for-nested-dictionary-and-re-arrange-few-aspects