Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading