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(CO
Solution 1:
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}
Post a Comment for "Cartesian Product Of Dictionary Keys And Values Python"