Creating multiple keys dictionaries from lists

Viewed 428

I was using pyomo and I have to create some dictionaries with multiple keys to work with it.

So, for example, I have these three lists below, and I want to associate Demand with both Product and Client.

They're already ordered and contain the same amount of entries.

Product = ["A","B","C","A","B","C"]

Client = ["Client1","Client1","Client1","Client2","Client2","Client2"]

Demand = [1,2,3,4,5,6]

And so I wanted the following output:

Demand_dict = {("A","Client1"):1, ("B","Client1"):2,("C","Client1"):3,("A","Client2"):4, ("B","Client2"):5,("C","Client2"):6,

I tried usind dict(zip) but I can't put multiple keys on th first argument.

Any easy way of doing it?

Thanks

1 Answers

This should give you the result you need using a dictionary comprehension:

Demand_dict = {(p, c): d for p, c, d in zip(Product, Client, Demand)}

It zips the three lists and then iterates over the 3-tuples using the first two values as the key for a dictionary entry and the third value as the value.

Related