anquadros anquadros - 5 months ago 9
Python Question

How to assert if I have specific unique values in a subdictionary?

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}}


Each
value_a
must be unique in comparison with other
value_a
.

Each
value_b
must be unique in comparison with other
value_b
.

Each
value_c
must be unique in comparison with other
value_c
.

etc...

I.e. if
dictionary['key01']['value_a']
is 1, this value CAN'T appear again in
dictionary['key02']['value_a']
and
dictionary['key03']['value_a']
.

I need to write a pytest-assert for that!

In the example, there's a error since
dictionary['key02']['value_c']
and
dictionary['key03']['value_c']
are equal.

Answer

Here you go:

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 in dictionary.keys():
    for key_second in dictionary.keys():
        if key_first != key_second:
            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

It requires a lot of loops and might be confusing at first, but what it does is:

  1. go through every key in the dictionary and compare it's value with every other keys value (but not with itself),
  2. compare values of all of the keys in the internal dictionary if they are present in both of them,
  3. if for any key the values are equal, throw AssertionError.

You can wrap that solution in a function by adding in the beggining:

def test_unique_values(dictionary: dict):
Comments