0

I was trying to make a code to help me a bit with statistics homework. The code does work, but the output is very unreadable since it's not sorted by numbers. Is there any way to sort the numbers in here? This is the code I have:

from time import sleep
numbers = {}
newList = []
total = 0
tempint = 0
keynum = 0
print("In this program you can input all the numbers given in a list, and you will get a result of how many numbers there are of any unique numbers, frequency, relavitve frequency and how many in total.")
sleep(2)
while True:
    inp = input("Enter a number in the list (press enter to stop the program)")
    if inp == '': break 
    if not f'{inp}' in numbers:
       numbers[f'{inp}'] = [1]
    else: numbers[f'{inp}'].append(1)
for key,value in numbers.items():   
    total += len(value)
for key,value in sorted(numbers.items()):
    freq = len(value)
    print(f'{key} - frequency: {freq}, relative frequency: {freq/total*100}%')
print(f'Total amount: {total}')
for key,value in numbers.items():
    tempint += int(key)                 
    keynum += 1
print(f'Unique numbers: {keynum}')
print(f'Average: {tempint/keynum}')

I want the output when I run the program look something like this:

1 - frequency: 2, relative frequency: 28.57142857142857% 2 - frequency: 1, relative frequency: 14.285714285714285% 3 - frequency: 3, relative frequency: 42.857142857142854% 4 - frequency: 1, relative frequency: 14.285714285714285% Total amount: 7 Unique numbers: 4 Average: 2.5 So basically sorted by the numbers placed in the beginning of the line which represent keys in a dictionary. I would appreciate any help.

no jif
  • 3
  • 4
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – jizhihaoSAMA Apr 23 '20 at 12:39
  • @njif Following the above link, changing this line `for key,value in sorted(numbers.items()):` to `for key,value in sorted(numbers.items(), key=lambda x: int(x[0])):` should work. – Axe319 Apr 23 '20 at 13:20

1 Answers1

0

You can use an OrderedDict to sort a dict by keys.

Tristan Nemoz
  • 1,844
  • 1
  • 6
  • 19
  • As of Python 3.6+ dictionaries maintain their order and you can just use `sorted(my_dict)`. – Axe319 Apr 23 '20 at 12:45
  • How can I use OrderedDict in my scenario? When I run the program, I need to input the keys themselves? – no jif Apr 23 '20 at 12:56