Local sorting does not need to assign a value to the key again.
import random
import time
from copy import deepcopy
def time_it(func):
def inner():
start = time.time()
func()
end = time.time()
print('time used:{} second'.format(end - start))
return inner
def random_l(n):
return [random.randint(0, 100) for _ in range(n)]
my_dict = {
'first': random_l(5),
'second': random_l(5),
'third': random_l(5)
}
my_dict1 = deepcopy(my_dict)
my_dict2 = deepcopy(my_dict)
@time_it
def foo():
print(my_dict1)
for key, values in my_dict1.items():
my_dict1[key] = sorted(values)
print(my_dict1)
@time_it
def bar():
print(my_dict2)
for key, values in my_dict2.items():
sorted(my_dict2[key])
print(my_dict2)
if __name__ == '__main__':
foo()
bar()
{'first': [28, 96, 52, 57, 93], 'second': [17, 89, 76, 30, 36], 'third': [73, 32, 9, 90, 81]}
{'first': [28, 52, 57, 93, 96], 'second': [17, 30, 36, 76, 89], 'third': [9, 32, 73, 81, 90]}
time used:5.3882598876953125e-05 second
{'first': [28, 96, 52, 57, 93], 'second': [17, 89, 76, 30, 36], 'third': [73, 32, 9, 90, 81]}
{'first': [28, 96, 52, 57, 93], 'second': [17, 89, 76, 30, 36], 'third': [73, 32, 9, 90, 81]}
time used:1.621246337890625e-05 second
If you want a feature like sortedList sortedcontainers is convenient, or you can use the insort function of the bitsect module