0

I want to know how I can sort a dictionary by key and then print the corresponding values ? Here is my dictionnary, it counts how many times a number appear in a list.

L=[1,2,1,5,9,7,8,0,3]
d = {}
for i in L:
    if i in d : d[ i ] += 1
    else : d[ i ] = 1

val= list(d.keys())  
frequency= list(d.values())
for i in range(len(d)):
  print(val[i],":",frequency[i])

I get

1 : 2
2 : 1
5 : 1
9 : 1
7 : 1
8 : 1
0 : 1
3 : 1

But I want the keys to appear in an ascending order, how can I do this and keep the corresponding value of the key ?

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
ferrou
  • 11
  • 1

1 Answers1

0

You can try:

print(sorted(d.items(), key=lambda x: x[0]))

the second option can be:

import operator
sorted_x = sorted(d.items(), key=operator.itemgetter(0))
print({k[0]:k[1] for k in sorted_x})

result:

{0: 1, 1: 2, 2: 1, 3: 1, 5: 1, 7: 1, 8: 1, 9: 1}
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88