CaPitaLizatIon is IMPORTANT - Looping in Python

21 October 2022

Today, I was attempting to iterate through a list and a dictionary and identify where elements in the list matched. From there, the goal was to create a new list, using the values from the dictionary to get a list of appropriate matching codes. Here is an example of what I was attempting to do:

 
sampleList = ['Apple', 'Banana', 'Orange', 'Nectarine', 'Pear', 'Apricot']
sampleDict = {'apple':1000,'banana':1100,'pear':1200,'nectarine':1500,'apricot':9999,'strawberry':1600, 'orange':1700}
  
for i in sampleList:
if i in sampleDict:
    print('True')
else:
    print('False')

This is a simplified version of what I needed to do; however, this snippet of code demonstrates the idea. If I were to run the code above, I would get "False" for each element as an output. This is because capitalization matters in Python, i.e., if the two words that are being compared have differences in capitalization, then they will not be evaluated to being equal. Though this is a simple concept, for long lists, it may not be apparent that there are inconsistencies in casing, until there are problems down the road in your project. To fix this, I simply needed to make both the list and dictionary be in the same case. This is where list comprehension came in handy! I ensured that every element in the list was the same as the cases of each key in the dictionary. I added in this line of code to accomplish this:

sampleList = [x.casefold() for x in sampleList]

I could have used any number of case functions; however, I felt it was best to use casefold() and have Python ignore casing for the list entirely. I used a similar list comprehension to accomplish the task for the dictionary. Ultimately, I wanted to return a new list that contained a list of the codes from the original list above. In this case, I want the output to look like:

  >>> [1000, 1100, 1700, 1500, 1200, 9999]

Notice that this new list contains the codes for each fruit in the original list, which were obtained from the dictionary dict. To accomplish this, I wrote a for loop similar to the one below. It is not optimized, but does ultimately accomplish the goal to return the appropriate output. The logic initializes an empty list, where the final output will be stored. Then a for loop is used to iterate through each element of the list and check if that value is a value in the dictionary. If there is a match between a value in the list and the dictionary, then that value is appended to new_list. This is the code that generates the desired output:


new_list = []
for i in sampleList:
if i in sampleDict:
    for key, value in sampleDict.items():
        if i == key:
              new_list.append(value)

The desired output could not be obtained if there were discrepancies with the casing. Differences in the casing would cause the if i in dict clause to evaluate to FALSE for any element that does not match the casing exactly with the dictionary.