python 嵌套字典表示复杂表格_Python:如何将嵌套字典打印为具有可变行的复杂表?...

给你(编辑):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列表中追加精确的列名!在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值