import collections
import math

def cmpr(a, b):
    print(a, b)
    if a[0]/r != b[0]/r:
        return a[0]/r < b[0]/r
    return a[1] < b[1]

a   = [1, 1, 2, 1, 3, 4, 5, 2, 8];
r = math.sqrt(len(a))
d_query = {0:[0, 4], 1:[5, 7], 2:[2, 4], 3:[5, 8]}
od = collections.OrderedDict(sorted(d_query.items(), cmpr, key= lambda x: x[1]))