Search code examples
pythonpython-2.7loopsnested-loopspython-2.x

Convert Pythonic approach of looping into nested loops


I am a beginner in Python. I'd like to understand the Pythonic approach of looping as I am a C coder for a long time. Given the following two lines:

{k: v for out_d in outs for k, v in out_d.iteritems()}
[{} for i in range(nthreads)]

Can someone break it down so that it follows the C standard approach of nested loops?


Solution

  • my_dict = {k: v for out_d in outs for k, v in out_d.iteritems()}
    
    # is equivalent to
    
    my_dict = {}
    for out_d in outs:
        for key, value in out_d.iteritems():
            my_dict[key] = value
    
    
    
    my_list = [{} for i in range(nthreads)]
    
    # is equivalent to
    
    my_list = []
    for i in range(nthreads):
        my_list.append({})