you can use input
and if-elif-else
to do it.
code:
def sort_by_key(d):
sort_d = sorted(d.items())
for i in sort_d:
print(i[0], i[1])
def sort_by_value(d):
sort_d = sorted(d.items(), key=lambda x: x[1])
for i in sort_d:
print(i[0], i[1])
d = {'b': 1, 'y': 12, 'c': 7, 'm': 2}
choose = input("Which sort function they want to be run? input 'key' or 'value'")
if choose == "key":
sort_by_key(d)
elif choose == "value":
sort_by_value(d)
else:
print("invaild input")
result:
Which sort function they want to be run? input 'key' or 'value'key
b 1
c 7
m 2
y 12
Which sort function they want to be run? input 'key' or 'value'value
b 1
m 2
c 7
y 12
Which sort function they want to be run? input 'key' or 'value'xxxx
invaild input
EDIT:with a little improve to remove duplicate code
code:
def sort(d,keyfunc = None):
sort_d = sorted(d.items(), key=keyfunc)
for i in sort_d:
print(i[0], i[1])
d = {'b': 1, 'y': 12, 'c': 7, 'm': 2}
operation_dic = {"key":None,"value":lambda x: x[1]}
while True:
choose = input("Which sort function they want to be run? input 'key' or 'value'")
if choose in operation_dic:
sort(d,operation_dic[choose])
break
else:
print("invaild input")