How to Sort Files by Name and Size in Python

Sort a list of file dictionaries by name then size using Python's sorted() with a lambda key.

Easy Python 3.9+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

18 lines
Python 3.9+
from pathlib import Path

def sort_files_data(files):
    """Sort a list of file dictionaries by name, then by size."""
    return sorted(files, key=lambda f: (f["name"], f["size"]))

if __name__ == "__main__":
    files_data = [
        {"name": "report.pdf", "size": 2048},
        {"name": "data.csv", "size": 1024},
        {"name": "photo.jpg", "size": 5120},
        {"name": "data.csv", "size": 2048},
        {"name": "notes.txt", "size": 256},
    ]
    
    sorted_files = sort_files_data(files_data)
    for f in sorted_files:
        print(f"{f['name']} - {f['size']} bytes")

Output

stdout
data.csv - 1024 bytes
data.csv - 2048 bytes
notes.txt - 256 bytes
photo.jpg - 5120 bytes
report.pdf - 2048 bytes

How it works

The code defines a function that uses sorted() with a key that returns a tuple (name, size). Python sorts tuples lexicographically, so file names are sorted alphabetically first, and files with the same name are then ordered by size in ascending order. The result is a new sorted list, leaving the original list unchanged.

Common mistakes

  • Forgetting that sorting is case-sensitive: 'Data.csv' sorts before 'data.csv'.
  • Using a list of file paths instead of dictionaries, which would require a different key extraction.
  • Assuming `sorted()` mutates the original list; it returns a new list instead.

Variations

  1. Use `f['size']` as the primary key and `f['name']` as secondary: `sorted(files, key=lambda f: (f['size'], f['name']))`.
  2. Use `operator.itemgetter('name', 'size')` for a more readable key.

Real-world use cases

  • Displaying a directory listing in a file manager, sorted by name then file size.
  • Preparing a list of files for a batch upload where you want consistent ordering.
  • Generating a report of files in a folder, sorted alphabetically and by size for easy review.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.