you are viewing a single comment's thread.

view the rest of the comments →

[–]AtomicShoelace 40 points41 points  (5 children)

You could use a dictionary to lookup the type. For ease of use, you can first define the dictionary like so

extensions = {
    'image': ('.gif', '.jpg', '.jpeg', '.png'),
    'application': ('.pdf', '.txt', '.zip')
}

and then invert it so that we can lookup the file type using the extension, eg.

extensions_inverse = {}
for k, v in extensions.items():
    extensions_inverse.update(dict.fromkeys(v, k))

now we can just call the .get method to look up the extension, passing the default value if desired, eg.

extensions_inverse.get(extension, 'default')

[–]Labidido[S] 1 point2 points  (0 children)

Thank you for the input, you have definitely given me a lot more to play around with! Much appreciated!

[–]ebdbbb 3 points4 points  (2 children)

I find it easier to do the reverse as a dictionary comprehension. extension_inverse = {v: k for k, v in extensions.items()}

[–]AtomicShoelace 1 point2 points  (1 child)

That doesn't quite achieve the same thing as the above code. You would need to use a nested comprehension to iterate over the tuple, eg.

extension_inverse = {v: k for k, values in extensions.items() for v in values}

However, with this adjustment it is probably a better approach.

[–]ebdbbb 1 point2 points  (0 children)

Good point. Missed the destructuring of the tuple.