In Python it is possible to index dictionaries with tuples.
I made use of this technique in one of my previous posts, covering constraint programming with Google OR-tools in Python.
I demonstrate the technique in the coding example below:
# declare empty dictionary dictObj = {} # adding elements, indexed (keyed) with a tuple for i in range(3): for j in range(3): dictObj[(i,j)] = i + j # print dictionary content print(dictObj)
{(0, 0): 0, (0, 1): 1, (0, 2): 2, (1, 0): 1, (1, 1): 2, (1, 2): 3, (2, 0): 2, (2, 1): 3, (2, 2): 4}
This technique is especially helpful when combined with list comprehensions in Python. See my post on job scheduling with Google OR-Tools and constraint programming in Python for a more sophisticated coding example.
Data scientist focusing on simulation, optimization and modeling in R, SQL, VBA and Python
Leave a Reply