1
numbers = ['3','1','6','5','4','4','3','2','1','4','3','5','4','9','84','7','878','6']
counts = dict()
for number in numbers:
    counts[number] = counts.get(number, 0) + 1
print counts

for k,v in sorted(counts.items()):
    print k,v

Output:

{'878': 1, '1': 2, '3': 3, '2': 1, '5': 2, '4': 4, '7': 1, '6': 2, '9': 1, '84': 1}
1 2
2 1
3 3
4 4
5 2
6 2
7 1
84 1
878 1
9 1 

Why is 9 the last one instead of 84 and 878?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Issam
  • 15
  • 4

3 Answers3

3

Because it compares lexicograhically. And '8' of '878' comes before '9' in lexicographical order. You are comparing as strings and not integers.

Priyansh Goel
  • 2,660
  • 1
  • 13
  • 37
0

Because you have put your numbers in as strings they are sorted lexicographically which puts things in order by the characters of the string. So '9' is compared to the first '8' of '898' and thus comes after it.

You can get a more natural sort order by using a package such as Natsort which can be installed via PyPi.

Jack Aidley
  • 19,439
  • 7
  • 43
  • 70
-1

Because you are comparing strings and you want to compare numbers.

Mad Wombat
  • 14,490
  • 14
  • 73
  • 109