Skip to content

Instantly share code, notes, and snippets.

@ztane
Last active October 9, 2018 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ztane/4f8c74b727e89ec156c414fe67f267af to your computer and use it in GitHub Desktop.
Save ztane/4f8c74b727e89ec156c414fe67f267af to your computer and use it in GitHub Desktop.
dictionary merging test
from collections import defaultdict
import time
i = 100
for _ in range(3):
list_of_dictionaries = [{1: 1} for i in range(i)]
list_of_dictionaries.append(dict.fromkeys(range(i)))
n = sum(map(len, list_of_dictionaries))
m = len(set().union(*list_of_dictionaries))
k = len(list_of_dictionaries)
km = k * m
print(f'\n\nn = {n}, m = {m}, k = {k}, km = {k * m}')
print('\ndefaultdict')
start = time.perf_counter()
dd = defaultdict(list)
for d in list_of_dictionaries:
for k, v in d.items():
dd[k].append(v)
dt = time.perf_counter() - start
print(f'time per n: {dt / n:0.12f}')
print(f'time per km: {dt / km:0.12f}')
print('\ncomprehension')
start = time.perf_counter()
allkeys = set().union(*list_of_dictionaries)
res = {k: [d[k] for d in list_of_dictionaries if k in d] for k in allkeys}
dt = time.perf_counter() - start
print(f'time per n: {dt / n:0.12f}')
print(f'time per km: {dt / km:0.12f}')
i = i * 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment