【发布时间】:2018-11-28 18:40:11
【问题描述】:
假设我有三个列表,并希望使用列表中的项目作为键和值来创建字典。我希望它看起来像这样:
main_dic = {'FL-01':{'existing': 22, 'proposed': 47}, 'FL-01P': {'existing': 5, 'proposed': 8}, 'P04A': {'existing': 14, 'proposed': 38}, 'P05': {'existing': 7, 'proposed': 95}}
所以,这是我的三个列表:
units = ['FL-01','FL-01P','P04A','P05']
existing = [22,5,14,7]
proposed = [47, 8, 38, 95]
我首先设置并清空字典
main_dic = dict()
现在是我感到困惑的地方,因为我需要它们保持秩序。我想我可以将现有的和提议的压缩在一起,但这只是一个简单的例子,如果我添加了第四个列表,比如future = [4, 7, 91, 26],那么这将不起作用。我想首先迭代抛出单位列表,因为它们将成为主字典的关键并以某种方式使用setdefault(k, v),但我不确定如何正确应用它。有什么建议么?
【问题讨论】:
标签: python-3.x list dictionary