How do I create a unique value for each key using dict.fromkeys? [duplicate]

The problem is that in

results = dict.fromkeys(inputs, [])

[] is evaluated only once, right there.

I’d rewrite this code like that:

runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = {}

for run in range(runs):
    for i in inputs:
        results.setdefault(i,[]).append(benchmark(i))

Other option is:

runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = dict([(i,[]) for i in inputs])

for run in range(runs):
    for i in inputs:
        results[i].append(benchmark(i))

Leave a Comment