lines = ''' 1.2.2.3 1.21.29.19.... ''' cnt = {} for line in lines.split(): if line not in cnt: cnt[line] = 0 cnt[line] += 1 print cnt out = cnt.items() out.sort(lambda a,b:-cmp(a[1],b[1])) print out