Sorting the keys will make this easier. Then keep track of the last number and the last group. While you're iterating through the keys, for each 2-digit group append the output to a string instead of printing it, and keep track of whether all of the groups so far match. When you get to the next group, decide if you can print one line for the group, and otherwise print the accumulated lines.