简体   繁体   中英

Python - unpacking a list of nametuples

I am using psutil.users() to get a list of namedtuples referencing each user on the system. I am trying to make a dictionary of just the names and terminal types and I am junking the rest. When I do this:

{user.name:user.terminal for user in psutil.users()}

I only get one of the users, not both. I know there are two there because I can print psutil.users() and see them both. I couldn't see what I was doing wrong so I did:

for user in psutil.users():
    print user.name
    print user.terminal

and it works just as intended. But my dict comprehension version doesn't. I can't see what I'm doing incorrectly.

In your case, it may be possible that both username is same and in dictionary we are required to have unique key. That is why you are getting only one key-value pair in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM