简体   繁体   English

Python-解压缩nametuple列表

[英]Python - unpacking a list of nametuples

I am using psutil.users() to get a list of namedtuples referencing each user on the system. 我正在使用psutil.users()获取引用系统上每个用户的namedtuple列表。 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. 我知道那里有两个,因为我可以打印psutil.users()并同时看到它们。 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. 这就是为什么在代码中仅获得一对键值对的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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