Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 484
Kyle Cronin Avatar asked Mar 17 '09 15:03

Kyle Cronin


People also ask

What is the use of Fromkeys () in dictionary?

The fromkeys() method returns a dictionary with the specified keys and the specified value.

What is the use of Fromkeys () give example?

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 .

How do you create a dictionary with multiple values per key?

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.


1 Answers

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))
like image 50
vartec Avatar answered Nov 06 '22 03:11

vartec