Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...