如何在现有字典dict_sample外层添加historical列表层级?
问题:如何将字典包裹在指定结构中?
原字典结构
dict_sample = { 'close': {'01/01/2022': 70327.6216, '02/01/2022': 69699.74376000001, '03/01/2022': 68400.97064, '04/01/2022': 67238.73537000001, '05/01/2022': 63901.21185000001, '06/01/2022': 63857.56575, '07/01/2022': 61243.99047, '08/01/2022': 61428.6952}, 'high': {'01/01/2022': 70592.20832, '02/01/2022': 70632.42668, '03/01/2022': 70059.4992, '04/01/2022': 69685.67126, '05/01/2022': 69189.04710000001, '06/01/2022': 64857.41691000001, '07/01/2022': 63574.54257, '08/01/2022': 62360.916040000004}, 'low': {'01/01/2022': 68087.621, '02/01/2022': 68825.25224, '03/01/2022': 67331.1328, '04/01/2022': 66893.72049, '05/01/2022': 62590.39965, '06/01/2022': 62944.24587, '07/01/2022': 60158.021, '08/01/2022': 59810.57563}, 'open': {'01/01/2022': 68087.621, '02/01/2022': 70328.65284, '03/01/2022': 69673.37348000001, '04/01/2022': 68116.52833, '05/01/2022': 67443.40665, '06/01/2022': 64352.60172, '07/01/2022': 63530.61439, '08/01/2022': 61250.77133}, 'volume': {'01/01/2022': 31239, '02/01/2022': 27020, '03/01/2022': 41062, '04/01/2022': 55589, '05/01/2022': 83744, '06/01/2022': 63076, '07/01/2022': 88358, '08/01/2022': 52544} }
需求
需要创建new_dict_sample,将dict_sample包裹在名为historical的列表结构中,最终格式如下:
{ 'historical': [ { 'close': {'01/01/2022': 70327.6216, '02/01/2022': 69699.74376000001, '03/01/2022': 68400.97064, '04/01/2022': 67238.73537000001, '05/01/2022': 63901.21185000001, '06/01/2022': 63857.56575, '07/01/2022': 61243.99047, '08/01/2022': 61428.6952}, 'high': {'01/01/2022': 70592.20832, '02/01/2022': 70632.42668, '03/01/2022': 70059.4992, '04/01/2022': 69685.67126, '05/01/2022': 69189.04710000001, '06/01/2022': 64857.41691000001, '07/01/2022': 63574.54257, '08/01/2022': 62360.916040000004}, 'low': {'01/01/2022': 68087.621, '02/01/2022': 68825.25224, '03/01/2022': 67331.1328, '04/01/2022': 66893.72049, '05/01/2022': 62590.39965, '06/01/2022': 62944.24587, '07/01/2022': 60158.021, '08/01/2022': 59810.57563}, 'open': {'01/01/2022': 68087.621, '02/01/2022': 70328.65284, '03/01/2022': 69673.37348000001, '04/01/2022': 68116.52833, '05/01/2022': 67443.40665, '06/01/2022': 64352.60172, '07/01/2022': 63530.61439, '08/01/2022': 61250.77133}, 'volume': {'01/01/2022': 31239, '02/01/2022': 27020, '03/01/2022': 41062, '04/01/2022': 55589, '05/01/2022': 83744, '06/01/2022': 63076, '07/01/2022': 88358, '08/01/2022': 52544} } ] }
尝试的错误代码
new_dict_sample = [{k : val[x] for k, val in dict_sample.items()} for x in range(2)]
错误原因分析
- 代码中
val[x]的写法完全错误:val是dict_sample里的子字典(比如close对应的日期-数值字典),其键是日期字符串,不存在整数索引x(0或1),会直接触发KeyError。 - 整体结构偏离需求:需求是生成一个外层字典(键为
historical),而你的代码生成的是一个列表,内部字典的结构也和目标完全不符。
正确实现代码
直接构造目标结构即可,无需复杂推导:
new_dict_sample = {'historical': [dict_sample]}
如果需要避免后续修改dict_sample影响new_dict_sample中的内容,可以使用深拷贝:
import copy new_dict_sample = {'historical': [copy.deepcopy(dict_sample)]}
内容的提问来源于stack exchange,提问作者leolapa
相关产品推荐
相关产品推荐

