JanB
JanB

Reputation: 199

Cartesian Product of Dictionary Keys and Values Python

I have two lists with data:

COURSES = [C1, C2, C3]
ROOMS = [R1, R2, R3]

and I already created a list of tuples containing their cartesian product:

L_CR = list(itertools.product(COURSES, ROOMS))
#print(L_CR): [('C1', 'R1'), ('C1', 'R2'), ('C1', 'R3'), ('C2', 'R1').....

Now I have created two dictionaries storing integer values about the amount of people attending a course and the maximum amount of people fitting into a room:

dic_courses = {'C1': 10, 'C2': 5, 'C3': 20}
dic_rooms = {'R1': 5, 'R2': 10, 'R3': 20}

What I can't figure out is how I can create a dictionary which has the tuples as keys and the absolut difference between the maximum amount of people possible for a room and the number of people attending a course. What I did so far was creating a dictionary which stores each tuple as a key and where each key gets assigned a value of 1:

Dic_Courses_Room_Capacity = {}
for Element in L_CR:    
    Dic_Courses_Room_Capacity_Temp = {Element: 1}
    Dic_Courses_Room_Capacity.update(Dic_Students_Room_Capacity_Temp)

Which results in:

#print(Dic_Courses_Room_Capacity): {('C1', 'R1'): 1, ('C1', 'R2'): 1, ('C1', 'R3'): 1...

But what I am looking for would be:

#print(Dic_Courses_Room_Capacity): {('C1', 'R1'): 5 , ('C1', 'R2'): 0, ('C1', 'R3'): 10

where e.g.: ('C1', 'R3'): 10 = abs('C1' -'R3') = abs(10-20) = abs(-10) = 10

So I have to update my existing dictionary (Dic_Courses_Room_Capacity) with all calculated combinations of the other two dictionaries. I tried to loop through those two dictionaries with two for loops but that resulted in always getting the same number for each key(=tuple).

Any ideas?

Upvotes: 2

Views: 1363

Answers (1)

Austin
Austin

Reputation: 26039

Simple iteration through two dictionaries, adding tuple and absolute difference to another:

dic_courses = {'C1': 10, 'C2': 5, 'C3': 20}
dic_rooms = {'R1': 5, 'R2': 10, 'R3': 20}

d = {}
for k1, v1 in dic_courses.items():
    for k2, v2 in dic_rooms.items():
        d.update({(k1, k2): abs(v1 - v2)})

print(d)

# {('C1', 'R1'): 5, ('C1', 'R2'): 0, ('C1', 'R3'): 10,
#  ('C2', 'R1'): 0, ('C2', 'R2'): 5, ('C2', 'R3'): 15,
#  ('C3', 'R1'): 15, ('C3', 'R2'): 10, ('C3', 'R3'): 0}

Or itertools.product way:

from itertools import product

dic_courses = {'C1': 10, 'C2': 5, 'C3': 20}
dic_rooms = {'R1': 5, 'R2': 10, 'R3': 20}

d = {}
for x, y in product(dic_courses, dic_rooms):
    d.update({(x, y): abs(dic_courses[x] - dic_rooms[y])})

print(d)

# {('C1', 'R1'): 5, ('C1', 'R2'): 0, ('C1', 'R3'): 10, 
#  ('C2', 'R1'): 0, ('C2', 'R2'): 5, ('C2', 'R3'): 15,
#  ('C3', 'R1'): 15, ('C3', 'R2'): 10, ('C3', 'R3'): 0}

Upvotes: 3

Related Questions