我使用的是 pyomo,我必须创建一些带有多个键的字典才能使用它。
例如,我有下面这三个列表,我想将 Demand 与 Product 和 Client 联系起来。
它们已经被订购并且包含相同数量的条目。
Product = ["A","B","C","A","B","C"]
Client = ["Client1","Client1","Client1","Client2","Client2","Client2"]
Demand = [1,2,3,4,5,6]
所以我想要以下输出:
Demand_dict = {("A","Client1"):1, ("B","Client1"):2,("C","Client1"):3,("A","Client2"):4, ("B","Client2"):5,("C","Client2"):6,
我尝试使用 dict(zip)
但我不能在第一个参数上放置多个键。
有什么简单的方法吗?
谢谢
答案 0 :(得分:3)
这应该会为您提供使用 dictionary comprehension 所需的结果:
Demand_dict = {(p, c): d for p, c, d in zip(Product, Client, Demand)}
它压缩三个列表,然后使用前两个值作为字典条目的键和第三个值作为值迭代三元组。