Here I have another quiz from the newsletter mentioned here:

“From the file /etc/passwd you must print out a dict sorted by key. The key of dict is field #1 and the value is field #3 of the passwd file. The lines beginning with # must be threated as comments.”

Seems not so hard, let’s propose this:

d = dict([(line.split(':')[0], line.split(':')[2])
          for line in open('/etc/passwd').readlines() if not line.startswith('#')])
for k, v in sorted(d.items()):
    print(k, v)

This time I tried to keep it as shorter as possible using the beloved Python listing comprehension, then converting the list to a dictionary with dict(). Let’s see which were the proposed answers, instead.

One plain version:

users = {}
with open('/etc/passwd') as f:
    for line in f:
        if not line.startswith("#"):
            user_info = line.split(":")
            users[user_info[0]] = user_info[2]

for username in sorted(users):
    print("{}:{}".format(username, users[username]))

and one with dictionary comprehension:

users =  { line.split(':')[0] : line.split(':')[2]
           for line in open('/etc/passwd')
           if not line.startswith('#') }
for username in sorted(users):
    print("{}:{}".format(username, users[username]))

This time, this last is very close to mine solution that instead is more old style. Which is the fastest one, then? I ran both of them on my Linux box with perf stat -r 100. Mine scores: 0,015599686 seconds and his: 0,015344643 seconds As one would expect is almost identical scores.

So close!