【问题标题】:How can I create an empty triple nested dictionary using dictionary comprehension?如何使用字典理解创建一个空的三重嵌套字典?
【发布时间】:2021-10-17 23:28:43
【问题描述】:

我有三个列表,我想使用字典理解将它们变成空的三重嵌套字典的键。 “Facility”是外键,“Products”是中间键,“Customer”是内键。我怎样才能做到这一点?提前致谢

以下是我需要制作成键的列表:

Facility = ['Fac-1', 'Fac-2','Fac-3','Fac-4','Fac-5']  
Products = ['45906','48402','80591','102795','107275','128067','129522',]  
Customer = ["Apple","Samsung","Huawei","Nokia","Motorolla"]

【问题讨论】:

  • 但是值是什么?
  • 请给出所需输出的具体示例。
  • 如果你不知道如何编写一个理解,你应该 a) 如果赶时间,只写 for 循环,或者 b) 去寻找一个关于理解的教程。
  • 没有值,我需要它为空,因为我将在优化模型 (PuLP) 的目标函数中使用这个嵌套字典。我提供的三个列表是嵌套字典的键,而不是值。一旦我运行它,模型本身就会赋值

标签: python dictionary-comprehension


【解决方案1】:

如果使用空字典,则意味着将空 lists 作为值。

您可以使用dict comprehension

>>> d = {f: {p: {c: [] for c in Customer} for p in Products} for f in Facility}

然后你会得到你描述的数据结构:

>>> d
{'Fac-1': {'102795': {'Apple': [], ...}, ...},
 'Fac-2': {'102795': {'Apple': [], ...}, ...},
 ...}

>>> d.keys()
dict_keys(['Fac-1', 'Fac-2', 'Fac-3', 'Fac-4', 'Fac-5'])

>>> d['Fac-1'].keys()
dict_keys(['45906', '48402', '80591', '102795', '107275', '128067', '129522'])

>>> d['Fac-1']['45906'].keys()
dict_keys(['Apple', 'Samsung', 'Huawei', 'Nokia', 'Motorolla'])

【讨论】:

    猜你喜欢
    • 2016-12-25
    • 2016-06-09
    • 2021-07-24
    • 2020-06-28
    • 1970-01-01
    • 2018-06-21
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多