One way to do this is simply to find the “closest” color. Suppose we have a set of colors. It should not cover all 16777216 possible rgb values, it should not even be in rgb, but for simplicity it might look something like this:
colors = {'red': (255,0,0), 'green': (0,255,0), 'blue': (0,0,255), 'yellow': (255,255,0), 'orange': (255,127,0), 'white': (255,255,255), 'black': (0,0,0), 'gray': (127,127,127), 'pink': (255,127,127), 'purple': (127,0,255),}
Lets you define a mechanism that tells us what we really mean by the “closest” color. In this case, I will use a simple Cartesian distance, but everything that can compare the two colors for how similar they are will do.
def distance(left, right): return sum((lr)**2 for l, r in zip(left, right))**0.5 class NearestColorKey(object): def __init__(self, goal): self.goal = goal def __call__(self, item): return distance(self.goal, item[1])
And that’s actually all we need. We can use the built-in min() (or max if your similarity function returns higher values for more similar colors)
>>> min(colors.items(), key=NearestColorKey((10,10,100))) ('black', (0, 0, 0)) >>> min(colors.items(), key=NearestColorKey((10,10,200))) ('blue', (0, 0, 255)) >>> min(colors.items(), key=NearestColorKey((100,10,200))) ('purple', (127, 0, 255)) >>>