【发布时间】:2018-02-11 07:58:15
【问题描述】:
数据集:
id = [1,2,3]
header = ['name','attack','defense']
stats = [['John',12,30], ['Amy',32,89], ['Lisa',45,21]]
我想以嵌套字典的形式获得输出。外部字典的键将是 id,值将是包含其他数据的字典。即:
dict = {
1: {'name': 'John', 'attack': 12, 'defense': 30},
2: {'name': 'Amy', 'attack': 32, 'defense': 89},
3: {'name': 'Lisa', 'attack': 45, 'defense': 21}
}
这是我当前的代码:
dict = {}
for i in id:
next_input = {}
for index, h in enumerate (header):
for sublist in stats:
next_input[h] = sublist[index]
dict[i] = next_input
由于最后一个 for 循环,它无法正常工作。内部字典的值只是替换自己,直到最后一个子列表。
如何更正此代码?
【问题讨论】:
标签: python python-2.7 dictionary nested