Sort digits in Python
1) Use collections.Counter

from collections import Counter. Counter is a subclass of dict that helps keep tallies. This way, you don't need .get(digit, 0) or if i in digit_counts, making your code look a bit cleaner.

2) Iterate in increasing order

Right now, you need a power variable to track which position to place the next digit in. If you iterated in the opposite direction (i.e. range(10)), you could do result *= 10 in each loop.

3) Use a for loop instead of while

Whenever you are iterating and incrementing/decrementing, you have the opportunity to use a for loop. In this case, for while digit_counts[i] &gt;= 1 you don't care about the number of iterations, so you can use the _ as a "throwaway variable".

4) Code localization

Move result = 0 down so that it's just above where it starts being used. Code localization improves readability - depending on your source, the human brain can only remember 4-7 things at once. The fewer variables your reader has to track, the better.

Final Result

from collections import Counter

def sort_digits(n):
  digit_counts = Counter()

  while n &gt; 0:
    digit_counts[n % 10] += 1
    n /= 10

  result = 0
  for i in range(10):
    for _ in range(digit_counts[i]):
      result = 10 * result + i

  return result