I’m writing a code to identify the subfix for a given number. I have a bunch of if statements to figure out the subfix. However I thought that a more elegant solution would be a dictionary. So I have the below dictionary:
The issue is, if I write 9 in subfix, the result is False. How do I access the elements in the tuple in the dictionary?
subfix = {(0, 4, 5, 6, 7, 8, 9, 11, 12, 13): 'th', 1: 'st', 2: 'nd', 3: 'rd'}
For example, I would like to write something simple like:
def subf(a):
if a in subfix:
ending = subfix.get(a)
print('We met on the ',a,ending,'.'sep='')
which would print ‘We met on the 1st.’ (but doesn’t work for 0,4,5,6,7,8,9,11,12,13) How do I get it to work for those elements?
You need to know what the operations you’re using actually do.
something in some_dictionaryisn’t whatever arbitrarily defined notion of “in” test you happen to want at the time. It tests whethersomethingis a key ofsome_dictionary.9is not a key ofsubfix, so9insubfixrightly returnsFalse.Take a step back and think about
subfixWhat does it do? What is it for? In a definition like this:I would say that
subfixrepresents a mapping from numbers to the suffix used for the ordinal version of each number. OTOH this definition:represents something like “a mapping from tuples of numbers that share a common ordinal suffix OR single numbers to their ordinal suffix”. What this definition represents is much more complex, and so using it is much more complex. If you have an arbitrary number and you want to find its ordinal suffix, you need to find out whether it is a key in the dictionary or whether it is an element of any of the keys of the dictionary. This means the dictionary doesn’t allow you to jump straight to the ordinal suffix from the number, nor does it allow you to quickly check whether any number is in the mapping. So I think it’s the wrong data structure to use in this case; a direct mapping from numbers to suffixes would be much easier to use.