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

前端 未结 3 651
情歌与酒
情歌与酒 2020-12-10 14:05

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

相关标签:
3条回答
  • 2020-12-10 14:31

    You can also do this if you don't want to learn anything new (although I recommend you do!) I'm curious as to which method is faster?

    results = dict.fromkeys(inputs)
    
    for run in range(0, runs):
        for i in inputs:
            if not results[i]:
                results[i] = []
            results[i].append(benchmark(i))
    
    0 讨论(0)
  • 2020-12-10 14:40

    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))
    
    0 讨论(0)
  • 2020-12-10 14:43

    Check out defaultdict (requires Python 2.5 or greater).

    from collections import defaultdict
    
    def benchmark(input):
        ...
        return time_taken
    
    runs = 10
    inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
    results = defaultdict(list) # Creates a dict where the default value for any key is an empty list
    
    for run in range(0, runs):
        for i in inputs:
            results[i].append(benchmark(i))
    
    0 讨论(0)
提交回复
热议问题