我有下面提到的元组列表,元组中的第一个元素是键,我想根据它生成特定格式的字典。你知道吗
# list variable
x = [
(('Fresh Vegetables', 'Hamel', '2006', "Jimmy's Ebony Sweet Peas"), 209034.60000000001),
(('Fresh Vegetables', 'Hamel', '2006', "Sue's Ebony Asparagus"), 217158.67000000001),
(('Fresh Vegetables', 'Mentor', '2007', "Jimmy's Ebony Sweet Peas"), 225630.60000000001),
(('Fresh Vegetables', 'Mentor', '2007',"Sue's Ebony Asparagus"), 233201.47),
(('Fresh Vegetables', 'Hamel', '2006', "Bubba's Ebony Corn on the Cob"), 317588.95000000001),
(('Fresh Vegetables','Mentor', '2007', "Bubba's Ebony Corn on the Cob"), 343151.59000000003),
(('Fresh Vegetables', 'Sioux Center', '2007', "John's Ebony Squash"), 401308.01 000000001)
]
我想要下面给出的词典结构。其中“total”键是该字典中每个字典元素的总和。你知道吗
finalX = {
'Fresh Vegetables':{
'Hamel':{
'2006':{
"Jimmy's Ebony Sweet Peas":209034.60000000001,
"Sue's Ebony Asparagus":217158.67000000001,
"Bubba's Ebony Corn on the Cob":317588.95000000001,
"total": 743782.22
}
"total":743782.22
},
'Mentor':{
'2007':{
"Jimmy's Ebony Sweet Peas":225630.60000000001,
"Sue's Ebony Asparagus":233201.47,
"Bubba's Ebony Corn on the Cob":343151.59000000003,
"total": 801983.66
}
"total":801983.66
},
'Sioux Center':{
'2007':{
"John's Ebony Squash":401308.01000000001
"total":401308.01
}
"total":401308.01
}
"total":1947073.89
}
}
我知道没有递归是不可能的,但我被困在那里。如何实施?我试过一些事,但做不到。你知道吗
迭代方法:首先将其设置为dict,然后添加小计:
创建字典:
添加所有小计(请参见下面的编辑以获取较短版本)
输出(重新格式化):
编辑避免多个完整的
for
迭代:更具可读性的解决方案。你知道吗
这只是词典的主要部分。我想说明的一点是,即使使用简单的递归,也可以实现一些通用的解决方案。你知道吗
但是,对于小计,它需要一些额外的操作,这在本解决方案中尚未涉及。你知道吗
这是一种方法:
相关问题 更多 >
编程相关推荐