Skip to main content
 首页 » 编程设计

python之如果我在子词典中有特定的唯一值,如何断言

2025年05月04日31Terrylee

dictionary = {'key01' : {'value_a': 1, 'value_b': 4, 'value_c': 1, 'value_d': 1}, 
            'key02' : {'value_a': 2, 'value_b': 5, 'value_c': 2, 'value_d': 6}, 
            'key03' : {'value_a': 3, 'value_b': 6, 'value_c': 2, 'value_d': 9}} 

与其他 value_a 相比,每个 value_a 必须是唯一的。
每个 value_b 与其他 value_b 相比必须是唯一的。
每个 value_c 与其他 value_c 相比必须是唯一的。
等等……

即如果 dictionary['key01']['value_a'] 为 1,则该值不能再次出现在 dictionary['key02']['value_a'] 和 字典['key03']['value_a']。

我需要为此编写一个pytest-assert!

在这个例子中,有一个错误,因为 dictionary['key02']['value_c'] 和 dictionary['key03']['value_c'] 是相等的.

请您参考如下方法:

给你:

dictionary = { 'key01': { 'value_a': 1, 'value_b': 4, 'value_c': 1, 'value_d': 1 }, 
               'key02': { 'value_a': 2, 'value_b': 5, 'value_c': 2, 'value_d': 6 }, 
               'key03': { 'value_a': 3, 'value_b': 6, 'value_c': 2, 'value_d': 9 } } 
 
for key_first, key_second in itertools.combinations(dictionary, 2): 
    for internal_key in dictionary[key_first].keys(): 
        if internal_key not in dictionary[key_second]: 
            continue 
        assert dictionary[key_first][internal_key] != dictionary[key_second][internal_key], \ 
            "Values in dictionary should be unique for the same keys!\n" + \ 
            "Invalid keys are " + key_first + " and " + key_second + "\n" + \ 
            "for values of " + internal_key 

一开始可能会令人困惑,但它的作用是:

  1. 遍历字典中的每个键并将它的值与其他键的值进行比较(但不与自身进行比较),
  2. 比较内部字典中所有键的值,如果它们都存在于它们中,
  3. 如果任何键的值相等,则抛出 AssertionError。

您可以通过在开头添加以下内容来将该解决方案包装在一个函数中:

def test_unique_values(dictionary: dict):