user2981194
user2981194

Reputation:

Trouble using casefold with dictionary

I'm trying to compare items in dictionaries that are all strings and ignore the case. Below is an example of how I'm trying to use it - it doesn't work, but what I'm wanting to happen is have Ad, aB, and RD get printed out. Instead I get a key error when it gets to 'ab' because I'm not using the syntax correctly. Any assistance on how I could do this would be appreciated.

test_vals = ['ad', 'ab', 'rD']
test_dict = {'ad': 'Ad', 'Ab': 'aB', 'RD': 'RD'}
for item in test_vals:
    print(test_dict[item.casefold()])

Upvotes: 0

Views: 265

Answers (2)

CodeMaven42
CodeMaven42

Reputation: 44

Code:

test_vals = ['ad', 'ab', 'rD']
test_dict = {'ad': 'Ad', 'Ab': 'aB', 'RD': 'RD'}

# Using a list comprehension to filter keys and retrieve corresponding values
result = [test_dict[key] for key in test_dict if key.lower() in map(str.lower, test_vals)]

Printing the result

print(result)

The list comprehension iterates through keys in test_dict.

key.lower() converts the current key to lowercase for case-insensitive comparison.

map(str.lower, test_vals) converts all elements in test_vals to lowercase for case-insensitive matching.

The condition key.lower() in map(str.lower, test_vals) checks if the lowercase version of the current key is present in the lowercase version of any element in test_vals.

If the condition is true, the corresponding value test_dict[key] is included in the result list.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155323

If you're looking up keys by casefolding, the keys had better be casefolded themselves. You can either replace the dict with one with the casefolded keys, e.g.:

test_dict = {key.casefold(): value for key, value in test_dict.items()}

or augment it with the folded variant (so either the original form or casefolded form can be looked up:

test_dict.update({key.casefold(): value for key, value in test_dict.items()})

The point is, if the key is not already in the common casefolded form within the dict, there is no solution that benefits from dict's features that will find the unfolded key in the dict using a folded key for lookup, hash maps can't do stuff like that.

Upvotes: 0

Related Questions