I have a collection of dictionaries declared as class variables (and stored in FILE_TYPES
) that define filetypes. I need to cycle through these dictionaries to pair filetype names (stored in the 'name' key) with filenames that are passed into the class. Which of the following ways to do this is more pythonic? Or, is there a better way altogether -- maybe some dict comprehension I'm missing?
First way:
filetype = [ftype for ftype in cls.FILE_TYPES if ftype['name'] in filename][0]
Second way:
for ftype in cls.FILE_TYPES:
if ftype['name'] in filename:
filetype = ftype
I am not stuck on this per se, but I'd like to know if either of these approaches is better (e.g., more or less pythonic), or if it makes no difference to anyone.
I generally try to avoid nested logic like you see in the second approach whenever possible if I'm coding in python (not sure why entirely, but at some point this habit was hammered into me by god-knows-who). However, accessing the invariably singular list element in the first method with [0]
also seems obnoxious.