dummker
dummker

Reputation: 325

Python read line from file and sort int descending

So I got this text file looking like this:

 PID     TTY              TIME          CMD
1000    pts/2           00:00:00        aash
9000    pts/2           00:00:00        bash
3000    pts/2           00:00:00        cash

What I want to end up with is some kind of dictionary where I save |(PID,CMD)| sorted by PID descending.

So it would look like this:

[(9000,bash),(3000,cash),(1000,aash)]

Any Ideas? This is how I read the file and save in dictionary.

dict = {}

with open('newfile.txt') as f:
     next(f)   #skipping first line
     for line in f:
        result[line.split()[3]] = int(line.split()[0])

Appreciate any kind of help! Thanks in advance !

Upvotes: 0

Views: 319

Answers (2)

Israel Unterman
Israel Unterman

Reputation: 13510

If you need to end up with a list, then best is to read the data into a list and then to sort it, here is how:

lst = []
with open('newfile.txt') as f:
    next(f)
    for line in f:
        if line.split() != '':  # watch out for empty lines
            a, b, c, d = line.split()
            lst.append((int(a), d))

lst = sorted(lst)
print(lst)

====
[(1000, 'aash'), (3000, 'cash'), (9000, 'bash')]

sorted() sorts by the first item on the tuple, so you can use it in its basic form.

If what you need is a dictionary where the keys are sorted, then you can use OrderedDict, just import it and add another line to the code:

from collections import OrderedDict

and then

d = OrderedDict(lst)
print(d)

And here is the result:

OrderedDict([(1000, 'aash'), (3000, 'cash'), (9000, 'bash')])

Upvotes: 1

dummker
dummker

Reputation: 325

So this is the solution:

import collections

result = {}

with open('newfile.txt') as f:
    next(f)
    for line in f:
        result[line.split()[3]] = int(line.split()[0])

print(collections.OrderedDict(sorted(result.items(), key=lambda t: t[1])))

This is what it prints out:

OrderedDict([('aash', 1000), ('cash', 3000), ('bash', 9000)])])

Upvotes: 1

Related Questions