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.
Python code
18 linesfrom 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
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
- Use `f['size']` as the primary key and `f['name']` as secondary: `sorted(files, key=lambda f: (f['size'], f['name']))`.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.