mercredi 28 octobre 2015

Python --- checking for a dictionary key which is a range of integers [duplicate]

This question already has an answer here:

I'm building a dictionary of manufacturers. It would look something like this:

mfgs =     {17491: 'DS', 6543: 'AC'}

In this scenario, I need to represent a range of integers that all refer to the same manufacturer. (e.g. 1 - 99 are all manufactured by DC)

I've seen that you can create a dictionary key in which a range is represented.

mfgs =     {17491: 'DS', 6543: 'AC', (1,99): 'DC'}

Later on, I will have an integer grabbed from an external file. Depending upon the value encountered, I will log the appropriate manufacturer into another file.

I am unclear on how to check for the presence of a valid key/value pair (whether a number or a range of numbers) and log "Unknown" if neither is found without building an expanding if/then that accounts for keys defined in the dictionary.

It seems like try/except is appropriate, but if 21 is encountered, mfg[21] fails and it shouldn't.

Aucun commentaire:

Enregistrer un commentaire