Python-从嵌套列表中创建字典

时间:2018-09-17 18:40:54

标签: python nested directory

我目前正在执行一项任务,我应该根据MA Crossovers做出交易决策。

我正在考虑一种涉及字典的方法,但是,我仍然对如何创建字典还是很缺乏经验。

我的想法是转换如下列表:

cross = [[2, 2], [3, 1], [6, 2], [9, 1], [12, 1]]

其中:[time_index,buy_index]

这样,它给我留下了一个类似的目录

{'0': 0, '1':0, '2':2, ... , '12':1 }

值0、1、2代表:什么都不做,分别购买和出售。

任何能从中收集知识的帮助,想法或资源都将受到高度赞赏!

1 个答案:

答案 0 :(得分:0)

您可以使用f-string将这些引号引入您的key

cross = [[2, 2], [3, 1], [6, 2], [9, 1], [12, 1]] 

new_dict = {}
new_dict['0'] = 0
new_dict['1'] = 1

for i in cross:
    new_dict[f'"{i[0]}"'] = i[1] 

print(new_dict)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 nest_dict.py 
{'0': 0, '1': 1, '"2"': 2, '"3"': 1, '"6"': 2, '"9"': 1, '"12"': 1}