Search code examples
pythonlistdictionaryoptimizationdictionary-comprehension

How do I write below code using dictionary comprehension


Need help to optimize below python code using dictionary comprehension. How can modify my code in such a way that using python special features

        container_status = {}
        active=[]
        inactive=[]
        not_found=[]
        if containers:
            for container in containers:
                inspect_dict = cli.inspect_container(container)
                state = inspect_dict['State']
                is_running = state['Status'] == 'running'
                if is_running:
                    active.append(container)
                else:
                    inactive.append(container)        
            container_status= {'active':active,'inactive':inactive,'not_found':not_found }     
            print(container_status)```

Solution

  • You can try this

    container_status = {}
    active=[]
    inactive=[]
    not_found=[]
    inspect_dict = cli.inspect_container('festive_bell')
    if containers:              
        ls_to_append = active if inspect_dict['State']['Status'] == 'running' else inactive
        for container in containers:
            ls_to_append.append(container)
        container_status= {'active':active,'inactive':inactive,'not_found':not_found }     
        print(container_status)
    

    Note that each time that it's run it will show all the containers as active or inactive since it's depends on cli.inspect_container('festive_bell') results all of them have the same results