Python: remove case-insensitive duplicates, keep the first spelling
Remove case-insensitive duplicates from a Python list while preserving order and the first spelling. Compare keys, keep original values, and handle edge cases.
You want "Tea", "tea" and "TEA" to count as one word, while displaying "Tea", the first spelling received. Lowercasing every string produces the right groups but loses the text you meant to keep.
In short
To remove case-insensitive duplicates and keep the first spelling, compare a normalized key and append the original string only when that key is new. A seen set records keys; a separate list preserves the original strings in arrival order. For ASCII strings, lower() is enough; for Unicode caseless matching, consider casefold() and your application's comparison rules.
Why does lower followed by dict.fromkeys lose the spelling?
Lowercasing replaces the original strings before deduplication. The first capital letter is already gone.
values = ["Tea", "tea", "TEA", "Mate"]print(list(dict.fromkeys(value.lower() for value in values)))print(list({value.lower(): value for value in values}.values()))$ python3 normalize.py['tea', 'mate']['TEA', 'Mate']The first line keeps normalized keys: "tea" and "mate". The second builds a dictionary with normalized keys and original strings as values. It keeps the first key's position but overwrites its value on every duplicate: "TEA" eventually wins.
That works for a "last spelling, first position" contract. To retain the first spelling, check whether the key exists before recording the string. The dictionary insertion order guide covers insertion rules; here the decision is what to compare and what to return.
How do you keep the first string without sorting?
Walk through the list in order and append a string only when its key is missing from seen.
def keep_first(values, ignore_case): seen = set() result = [] for value in values: key = value.lower() if ignore_case else value if key not in seen: seen.add(key) result.append(value) return result
values = ["Tea", "tea", "TEA", "Mate"]print(keep_first(values, True))print(keep_first(values, False))print(values)print(keep_first(values, True) is values)$ python3 keep.py['Tea', 'Mate']['Tea', 'tea', 'TEA', 'Mate']['Tea', 'tea', 'TEA', 'Mate']Falsekey is used for duplicate detection. value remains the string to keep. With ignore_case=False, the key is the full string, so the three spellings remain distinct. With True, all three share the key "tea".
Result order comes from visiting values and appending to result. It doesn't depend on set iteration order: the code never iterates over the set. Sorting would change the contract; converting the original strings directly to a set would lose the ordering guarantee.
Step 1 of 3
Read Tea
- key
- tea
- result
- ['Tea']
- 0Teakept
- 1tea
- 2TEA
- 3Mate
The key tea is new. The original string Tea enters the result.
Read all steps
1. Read Tea
- key
- tea
- result
- ['Tea']
- 0Teakept
- 1tea
- 2TEA
- 3Mate
The key tea is new. The original string Tea enters the result.
2. Read tea then TEA
- key
- tea
- result
- ['Tea']
- 0Teakept
- 1teaduplicate
- 2TEAduplicate
- 3Mate
The key tea already exists. Neither string replaces Tea.
3. Read Mate
- key
- mate
- result
- ['Tea', 'Mate']
- 0Teakept
- 1teaduplicate
- 2TEAduplicate
- 3Matekept
The key mate is new. Mate is appended after Tea.
The function creates a new list even when the input is empty or has no duplicates. It leaves values unchanged. The example's is check verifies that input and result are distinct objects; comparing their values alone wouldn't establish that.
What happens to empty strings and spaces?
They remain data. Ignoring case doesn't authorize dropping empty strings or stripping spaces.
def keep_first(values, ignore_case): seen = set() result = [] for value in values: key = value.lower() if ignore_case else value if key not in seen: seen.add(key) result.append(value) return result
print(keep_first([], True))print(keep_first(["", "X", "", "x"], True))print(keep_first(["Tea", " tea", "TEA ", "tea"], True))$ python3 edges.py[]['', 'X']['Tea', ' tea', 'TEA ']The empty key is recorded just like any other. "Tea", " tea" and "TEA " remain three distinct groups because lower() preserves spaces. The final string "tea" joins the "Tea" group.
If you also need cleanup, define that separately: should the returned strings retain their spaces, should empty results be removed, and does comparison happen before or after cleanup? The strip and removeprefix guide covers that choice. Don't silently add cleanup to a function whose job is deduplication.
dedupe_keep_first
Implement dedupe_keep_first(values, ignore_case) for ASCII strings. Preserve the order and spelling of first occurrences, return a new list, and leave the input unchanged, including empty strings and spaces.
Is lower enough for every language?
No. casefold() supports Unicode caseless matching and can equate strings that lower() keeps distinct.
words = ["Straße", "STRASSE"]print([word.lower() for word in words])print([word.casefold() for word in words])print("é".casefold() == "e".casefold())print("é".casefold() == "e\u0301".casefold())$ python3 unicode.py['straße', 'strasse']['strasse', 'strasse']FalseFalseFor that Unicode contract, use value.casefold() as the comparison key while still appending value. This groups "Straße" and "STRASSE" together. The exercise only accepts ASCII strings and doesn't require this extension.
The last two lines also show the limits: ignoring case doesn't mean ignoring accents, and it doesn't automatically normalize composed and decomposed Unicode representations. A comparison rule for names or identifiers must explicitly decide those equivalences. This loop alone isn't a complete policy for login identifiers.
Frequently asked questions
Why not use list(set(values))?
A set compares strings as given and doesn't guarantee arrival order. That doesn't satisfy either case-insensitive matching or first-position preservation.
Can I keep the last spelling?
Yes. Updating a dictionary from normalized keys to original strings retains the last value at the first key's position. That isn't the order of the last occurrences.
Does this function count duplicates?
No. It keeps one representative per key. For frequencies, read the Counter guide and decide whether counts should refer to original strings or normalized keys.
Does the original list change?
No. The function appends the received strings to a new list. For mutable objects under a different contract, a new outer list wouldn't be a deep copy of its elements.
Sources
