Convert two lists into a dictionary

前端 未结 18 2485
囚心锁ツ
囚心锁ツ 2020-11-21 04:35

Imagine that you have:

keys = [\'name\', \'age\', \'food\']
values = [\'Monty\', 42, \'spam\']

What is the simplest way to produce the foll

18条回答
  •  清酒与你
    2020-11-21 05:15

    I had this doubt while I was trying to solve a graph-related problem. The issue I had was I needed to define an empty adjacency list and wanted to initialize all the nodes with an empty list, that's when I thought how about I check if it is fast enough, I mean if it will be worth doing a zip operation rather than simple assignment key-value pair. After all most of the times, the time factor is an important ice breaker. So I performed timeit operation for both approaches.

    import timeit
    def dictionary_creation(n_nodes):
        dummy_dict = dict()
        for node in range(n_nodes):
            dummy_dict[node] = []
        return dummy_dict
    
    
    def dictionary_creation_1(n_nodes):
        keys = list(range(n_nodes))
        values = [[] for i in range(n_nodes)]
        graph = dict(zip(keys, values))
        return graph
    
    
    def wrapper(func, *args, **kwargs):
        def wrapped():
            return func(*args, **kwargs)
        return wrapped
    
    iteration = wrapper(dictionary_creation, n_nodes)
    shorthand = wrapper(dictionary_creation_1, n_nodes)
    
    for trail in range(1, 8):
        print(f'Itertion: {timeit.timeit(iteration, number=trails)}\nShorthand: {timeit.timeit(shorthand, number=trails)}')
    

    For n_nodes = 10,000,000 I get,

    Iteration: 2.825081646999024 Shorthand: 3.535717916001886

    Iteration: 5.051560923002398 Shorthand: 6.255070794999483

    Iteration: 6.52859034499852 Shorthand: 8.221581164998497

    Iteration: 8.683652416999394 Shorthand: 12.599181543999293

    Iteration: 11.587241565001023 Shorthand: 15.27298851100204

    Iteration: 14.816342867001367 Shorthand: 17.162912737003353

    Iteration: 16.645022411001264 Shorthand: 19.976680120998935

    You can clearly see after a certain point, iteration approach at n_th step overtakes the time taken by shorthand approach at n-1_th step.

提交回复
热议问题