0

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)```
Aaditya R Krishnan
  • 495
  • 1
  • 10
  • 31

1 Answers1

1

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

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
  • Issues is `active.append(container)` returns None since append is in-place. – DarrylG Apr 07 '20 at 13:14
  • It's supposed to return None but still to assign the container into the expected list – Leo Arad Apr 07 '20 at 13:37
  • I see you're using it as a side effect. But, confusing since [Is it Pythonic to use list comprehensions for just side effects?](https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects) – DarrylG Apr 07 '20 at 13:43
  • Understood, I edit the code to do the same with one more line. – Leo Arad Apr 07 '20 at 13:50
  • There is no need to run over the list since the value is the same to all containers so you can just do it by an if statement – Leo Arad Apr 07 '20 at 13:57
  • You want `active.append(container)` rather than `active.extend(container)` otherwise if containers are lists, active will just be all the container lists merged together. – DarrylG Apr 07 '20 at 14:05
  • On your code when you run on each container for containers and append the container to the active/inactive lists it's the same as active/inactive.extend(containers) since it's chacking if inspect_dict['State']['Status'] is the same to all of them – Leo Arad Apr 07 '20 at 14:15
  • To change the extend to append? – Leo Arad Apr 07 '20 at 16:00