【发布时间】:2021-03-23 13:03:57
【问题描述】:
我正在尝试从列表中提取值并将其填充到嵌套字典中。
输入:
['abc-bcd_10_01_physics_90_70_20',
'abc-bcd_10_01_chemistry_85_75_10',
'ac-bd_10_03_biology_60_50_10',
'ad-bcd_10_05_physics_70_50_20',
'ac-bd_10_03_physics_65_50_15']
预期输出:
[
{'first-name' : 'abc',
'last-name' : 'bcd',
'class' : '10',
'roll-number' : 1,
'marks' : [{'subject':'physics',
'total' : 90,
'theory' : 70,
'practical' : 20},
{'subject':'chemistry',
'total' : 85,
'theory' : 75,
'practical' : 10}]
},
{'first-name' : 'ac',
'last-name' : 'bd',
'class' : '10',
'roll-number' : 3,
'marks' : [{'subject':'biology',
'total' : 60,
'theory' : 50,
'practical' : 10},
{'subject':'physics',
'total' : 65,
'theory' : 50,
'practical' : 15},
]
},
{'first-name' : 'ad',
'last-name' : 'bcd',
'class' : '10',
'roll-number' : 5,
'marks' : [{'subject':'physics',
'total' : 70,
'theory' : 50,
'practical' : 20}]
}
]
我可以使用 split 函数从输入列表中提取值并将其填充到一个普通字典中,但停留在我需要按键分组的点 first-name,last-name,class, roll-number 并在一个名为 marks 的通用键下收集其他键的列表。
另外,我需要字典中的键与上面指定的顺序相同。
【问题讨论】:
-
到目前为止你尝试过什么?请分享您当前遇到的代码。
标签: python dictionary nested dictionary-comprehension ordereddictionary