Using timeit
to compare merging dictionaries in #Python: Old way with **
unpacking vs. new way with |
.
timeit
runs the code 1000 times, using globals
to pass variables, and prints the timing results:
import timeit
dict1 = {f'key{i}': i for i in range(10000)}
dict2 = {f'key{i}': i for i in range(5000, 15000)}
old_way_time = timeit.timeit('''
merged_dict = {**dict1, **dict2}
''', globals=globals(), number=1000)
new_way_time = timeit.timeit('''
merged_dict = dict1 | dict2
''', globals=globals(), number=1000)
print(f"Old way time: {old_way_time:.6f} seconds")
print(f"New way time: {new_way_time:.6f} seconds")
# Old way time: 0.222962 seconds
# New way time: 0.222384 seconds
#timeit