Python – When to use a dictionary vs tuple in Python

dictionarypython

The specific example in mind is a list of filenames and their sizes. I can't decide whether each item in the list should be of the form {"filename": "blabla", "size": 123}, or just ("blabla", 123). A dictionary seems more logical to me because to access the size, for example, file["size"] is more explanatory than file[1]… but I don't really know for sure. Thoughts?

Best Answer

I would use a namedtuple:

from collections import namedtuple
Filesize = namedtuple('Filesize', 'filename size')
file = Filesize(filename="blabla", size=123)

Now you can use file.size and file.filename in your program, which is IMHO the most readable form. Note namedtuple creates immutable objects like tuples, and they are more lightweight than dictionaries, as described here.