Skip to content
Advertisement

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. 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.

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

Advertisement

Answer

If I understood your question correctly, you’re resetting the userlist inside the loop. 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()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement