First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use dict.fromkeys
(or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and I'd like for the key to be the input variable and the list to contain the times for the runs:
def benchmark(input):
...
return time_taken
runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = dict.fromkeys(inputs, [])
for run in range(0, runs):
for i in inputs:
results[i].append(benchmark(i))
The problem I'm having is that all the keys in the dictionary appear to share the same list, and each run simply appends to it. Is there any way to generate a unique empty list for each key using fromkeys
? If not, is there another way to do this without generating the resulting dictionary by hand?
The fromkeys() method returns a dictionary with the specified keys and the specified value.
Example 1: Python Dictionary fromkeys() with Key and Value In the above example, we have used the fromkeys() method to create the dictionary with the given set of keys and string value . Here, the fromkeys() method creates a new dictionary named vowels from keys and value .
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With