How can I print a list of process names and their values from a dictionary for each process?

I have a function that returns a dictionary of processes here is a snippet…

from win32com.client import GetObject
wmi = GetObject("winmgmts:")
def get_processes():
    dictprocesses =  {"Caption": [], "Creation Date": []}
    colprocs = wmi.ExecQuery("Select * from Win32_Process)
    for item in colprocs:
        dictprocesses["Caption"].append(item.Caption)
        dictprocesses["Creation Date"].append(item.CreationDate)
    return dictprocesses

I printed the the dictionary like this…

d = get_processes()
for key, value in d.items():
for v in value:
    print(key, v)

Output for each process:
Caption: <>
Caption: <>
Creation Date: <>
Creation Date: <>

I want to print the dictionary so that it looks like this…

First Process...
Caption: <>
Creation Date: <>

Second Process...
Caption: <>
Creation Date: <>

Etc...

>Solution :

In your code, the second loop continues to run for every value in a key, that’s why the output.

One of the ways to get the expected output could be,

d = get_processes()

temp_len = len(d["caption"])
i = 0

for i in range(temp_len):
   for key, value in d.items():
      print(key, value[i])
   i += 1

Leave a Reply