You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. 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.
  2. Broken Logic: Your loop returns False as soon as it finds any key (including the key k itself) with the same value as k. That's why when you test with k='a', the first iteration checks key='a', sees the values match, and immediately returns False—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:47:41