Python字典指定键值重复检测函数实现及逻辑修正问询
Fixing Your Dictionary Value Uniqueness Check Function
Let's walk through what's wrong with your current code and how to fix it to get the behavior you want.
First, the Issues in Your Current Code
- Redundant Condition: You've written the exact same
if (x.get(key) == x.get(k))check twice—this is totally unnecessary and doesn't change the logic at all; it's just duplicated code you can remove. - Broken Logic: Your loop returns
Falseas soon as it finds any key (including the keykitself) with the same value ask. That's why when you test withk='a', the first iteration checkskey='a', sees the values match, and immediately returnsFalse—which is the opposite of what you want.
Correct Implementations
We need to check if the value associated with k appears more than once across the entire dictionary. Here are a couple of clean ways to do this:
Option 1: Explicit Counting (With Early Termination)
This approach counts occurrences of the target value and stops early once we find a duplicate, which is efficient for large dictionaries:
def uniq(x, k): # First, handle the case where the key doesn't exist in the dictionary if k not in x: return True # Or raise ValueError("Key not found in dictionary") if you prefer target_value = x[k] occurrence_count = 0 for value in x.values(): if value == target_value: occurrence_count += 1 # If we find more than one occurrence, we can stop early if occurrence_count > 1: return False # If we finish the loop and only found one occurrence, return True return True
Option 2: Concise Count with List Method
If you prefer shorter code, you can use the count() method on the list of dictionary values:
def uniq(x, k): if k not in x: return True target_value = x[k] # Count how many times the target value appears in all values return list(x.values()).count(target_value) == 1
Testing the Fixed Code
Let's run your test cases to verify:
d1 = {'a': 1, 'b': 2, 'c': 2, 'd': 4} print(uniq(d1, 'a')) # Output: True (value 1 only appears once) print(uniq(d1, 'c')) # Output: False (value 2 appears twice)
Both implementations will give you the exact behavior you're looking for.
内容的提问来源于stack exchange,提问作者user13316483
相关产品推荐
相关产品推荐

