【问题标题】:Create a complex dictionary using multiple lists使用多个列表创建复杂字典
【发布时间】: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


    【解决方案1】:

    您使用zip 是正确的:

    units = ['FL-01','FL-01P','P04A','P05']
    existing = [22,5,14,7]
    proposed = [47, 8, 38, 95]
    
    d = {u: {'existing': e, 'proposed': p} for u, e, p in zip(units, existing, proposed)}
    
    print(d)
    # {'FL-01': {'existing': 22, 'proposed': 47},
    #  'FL-01P': {'existing': 5, 'proposed': 8},
    #  'P04A': {'existing': 14, 'proposed': 38},
    #  'P05': {'existing': 7, 'proposed': 95}}
    

    【讨论】:

    • 这非常有效。出于某种原因,我认为我一次只能压缩 2 个列表并且没有考虑使用字典理解。谢谢。
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 2020-04-28
    • 2019-08-09
    • 2021-09-04
    • 2011-10-20
    相关资源
    最近更新 更多