给你(编辑):import csv, itertools
d = {'Ben': {'wo_mana': ['Strength = 1.10'], 'wi_mana': ['Int = 1.20'], 'Skill': 'true', 'Magic': 'false'},
'Tom': {'wi_mana': ['Int = 1.40'], 'wo_mana': ['Agility = 1.60'], 'Skill': 'true', 'Magic': 'true'}}
header = ['Name', 'Skill', 'Magic', 'wo_mana', 'wi_mana']
with open('output.csv', 'w') as f:
w = csv.DictWriter(f, header)
w.writeheader()
for key, val in sorted(d.items()):
row = {'Name': key}
# print val
wo_mana = [item for item in val['wo_mana']]
wi_mana = [item for item in val['wi_mana']]
val['wo_mana'] = wo_mana[0]
val['wi_mana'] = wi_mana[0]
row.update(val)
w.writerow(row)
dict_list = []
if len(wi_mana) > len(wo_mana):
for index, item in enumerate(wo_mana):
dict_ = {}
dict_['wi_mana'] = wi_mana[index]
dict_['wo_mana'] = wo_mana[index]
# print dict_
dict_list.append(dict_)
[dict_list.append({'wi_mana': item}) for item in wi_mana[len(wo_mana):]]
else:
for index, item in enumerate(wi_mana):
dict_ = {}
dict_['wi_mana'] = wi_mana[index]
dict_['wo_mana'] = wo_mana[index]
# print dict_
dict_list.append(dict_)
[dict_list.append({'wo_mana': item}) for item in wo_mana[len(wi_mana):]]
# print dict_list
if len(dict_list) > 1:
[w.writerow(dict_) for dict_ in dict_list[1:]]
这很管用!告诉我。在
编辑:
根据问题:However, the number of values for wo_mana and wi_mana is unfixed, which can be 1, 2, 3, 4 etc.
所以我假设不会有键盘错误。
根据评论中修改后的陈述,解决方法如下:
它没有在各种条件下进行适当的测试,根据我从评论中了解到的,它工作良好,如果有任何问题,请告诉我:
^{pr2}$
该解决方案是高度通用的,您可以添加任意数量的manas/列,它将起作用。记住在header列表中追加精确的列名!在