Handling TypeError with defaultdict in Python 3.9 when using a custom key function
I'm working on a project where I need to count the occurrences of specific items in a list. To achieve this, I'm using `collections.defaultdict` with a custom key function that normalizes the values to lowercase. However, I'm working with a `TypeError` when I try to access the dictionary with keys that were not originally in the list. Here's a simplified version of my code: ```python from collections import defaultdict def normalize_key(key): return key.lower() if isinstance(key, str) else key items = ['Apple', 'Banana', 'apple', 'banana', 'APPLE'] count_dict = defaultdict(int) for item in items: norm_key = normalize_key(item) count_dict[norm_key] += 1 # Attempting to access a non-existing key try: print(count_dict['orange']) # This raises a TypeError except TypeError as e: print(f'behavior: {e}') # Output: behavior: unhashable type: 'list' ``` In this case, I'm trying to access a key that doesn't exist in the dictionary, which should ideally return `0`, but instead, I'm getting a `TypeError`. I've checked the normalization function, and it seems to be working fine, as it only converts strings to lowercase. I suspect the scenario arises from how I'm using the `defaultdict`. Is there any way to handle non-existing keys gracefully without triggering a `TypeError`? Additionally, is there a more efficient way to structure this counting process? Any help would be appreciated!