If a dictionary is required, note that there's a package called sortedcontainers which has a SortedDict that essentially would solve the sorting issue for you. To use it, all you'd need to change is initializing D_pair_value as a SortedDict() instead of a dict. Using your example setup: