Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

python - Creating multiple keys dictionaries from lists

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

question from:https://stackoverflow.com/questions/65848732/creating-multiple-keys-dictionaries-from-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...