简体   繁体   English

Python - 使用文件中的数组订购字典

[英]Python - Ordering a dictionary with the array from file

I have been trying to fetch the last and first field from the /etc/passwd file in linux.我一直在尝试从 linux 中的/etc/passwd文件中获取最后一个和第一个字段。 I want to fetch the last fields of the file( the shell which users are using ) and the first field( number of users using the shell ) and add it to a list.我想获取文件的最后一个字段(用户正在使用的外壳)和第一个字段(使用外壳的用户数)并将其添加到列表中。 For eg my final output must be something like例如,我的最终输出必须类似于

 {"/bin/bash/:[username1,username2],"/usr/sbin/nologin": [username2]}

Basically I want the key of the dictionary to be the shell and its value must be an array of users.基本上我希望字典的键是 shell,它的值必须是一个用户数组。

For this I have tried the below code为此,我尝试了以下代码

password_file = '/etc/passwd'
handler = open(password_file)
empty_dict = {}

for line in handler:
    last_line = line.split(':')[6]       #to fetch last line
    first_line = line.split(':')[0]           #to fetch first line
    userlist[]                               #create an array for users
    userlist.append(first_line)
    if(first_line not in last_line):
      empty_dict[last_line] = userlist     #adding the user array to the dict as value
      print(empty_dict)

This gives the output but this doesn't involve all the users to the dictionary key.这给出了输出,但这并不涉及字典键的所有用户。 Can you guys help me on which logic I went wrong.你们能帮我解决我出错的逻辑吗? Any help would be great.任何帮助都会很棒。 Thank you谢谢

If I understood your question correctly, you're resetting the userlist inside the loop.如果我理解正确你的问题,你重新设置userlist内循环。 Here is one possible way of doing this:这是执行此操作的一种可能方法:

from collections import defaultdict

password_file = '/etc/passwd'
handler = open(password_file)

userlist = defaultdict(list)
for line in handler:
    first, *_, last = line.strip().split(':')
    if first not in last:
      userlist[last or 'nologin'].append(first)

handler.close()

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

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