def nearest_colour_index(colour_map, rgb, debug=0):
 best_metric = ((3 * 256) * 256)
 best_colourx = 0
 for (colourx, cand_rgb) in colour_map.items():
  if (cand_rgb is None):
   continue
  metric = 0
  for (v1, v2) in zip(rgb, cand_rgb):
   metric += ((v1 - v2) * (v1 - v2))
  if (metric < best_metric):
   best_metric = metric
   best_colourx = colourx
   if (metric == 0):
    break
 if (0 and debug):
  print(('nearest_colour_index for %r is %r -> %r; best_metric is %d' % (rgb, best_colourx, colour_map[best_colourx], best_metric)))
 return best_colourx

def nearest_colour_index ( colour_map , rgb , debug = 0 ) : best_metric = ( ( 3 * 256 ) * 256 ) best_colourx = 0 for ( colourx , cand_rgb ) in colour_map . items ( ) : if ( cand_rgb is None ) : continue metric = 0 for ( v1 , v2 ) in zip ( rgb , cand_rgb ) : metric += ( ( v1 - v2 ) * ( v1 - v2 ) ) if ( metric < best_metric ) : best_metric = metric best_colourx = colourx if ( metric == 0 ) : break if ( 0 and debug ) : print ( ( 'nearest_colour_index for %r is %r -> %r; best_metric is %d' % ( rgb , best_colourx , colour_map [ best_colourx ] , best_metric ) ) ) return best_colourx
general purpose function .