0

I have the original variable:

files = {'1.txt' : [{'Line number': 1, 'file number': 1},
                   {'Line number': 2, 'file number': 1}],
         '2.txt' : [{'Line number': 1, 'file number': 2}]
        }

I need to sort the files by 'Line number' (although reverse, from least to the most, like this:

2.txt
total lines 1
Line number 1 file number 2
1.txt
total lines 2
Line number 1 file number 1
Line number 2 file number 1 

I was writing code, but I have stuck with many lines and made it very complex. Any idea about simpler few lines of code?

1
  • Please edit your question and post what you have tried so far. Commented Nov 5, 2022 at 18:29

1 Answer 1

1

Something like this?

sorted_files = {
    f: sorted(ll, key=lambda x: x['Line number'])
    for f, ll in sorted(files.items(), key=lambda x: len(x[1]))
}

Printing sorted_files you get:

for f, ll in sorted_files.items():
    print(f'{f}\ntotal lines {len(ll)}')
    for l in ll:
        print(' '.join([f'{k} {v}' for k, v in l.items()]))
2.txt
total lines 1
Line number 1 file number 2
1.txt
total lines 3
Line number 1 file number 1
Line number 2 file number 1
Line number 3 file number 4

Note: starting from Python 3.6 onwards, the dict type keeps the order of the insertion. So, iterating through the items of sorted_files, you will always get the right sequence of items. If you are using an older version of Python, you should not use a dict if you want to keep the order of the items, but instead, you should use a tuple of tuples or a list of lists (or any combination of list and tuple). So, you should use the following code:

sorted_files = [
    (f, sorted(ll, key=lambda x: x['Line number']))
    for f, ll in sorted(files.items(), key=lambda x: len(x[1]))
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.