Related Articles
Python | Test if dictionary contains unique keys and values
• Last Updated : 29 Apr, 2019

Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it. Let’s test various ways in which this can be done.

Method #1 : Using loops
In the Naive method to perform this particular task, we can check for each value and insert each value in list/hash in dictionary and when i’l repetition occurs, just stop the flow and return false.

 `# Python3 code to demonstrate``# check for unique values``# Using loops`` ` `# initializing dictionary``test_dict ``=` `{``'Manjeet'` `: ``1``, ``'Akash'` `: ``2``, ``'Akshat'` `: ``3``, ``'Nikhil'` `: ``1``}`` ` `# printing original dictionary``print``(``"The original dictionary : "` `+` `str``(test_dict))`` ` `# using loops``# check for unique values``flag ``=` `False``hash_val ``=` `dict``()``for` `keys ``in` `test_dict:``    ``if` `test_dict[keys] ``in` `hash_val:``        ``flag ``=` `True``        ``break``    ``else` `:``        ``hash_val[test_dict[keys]] ``=` `1`` ` `# print result``print``(``"Does dictionary contain repetition : "` `+` `str``(flag))`
Output :
```The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True
```

Method #2 : Using `len() + set() + values()`
This problem can be easily solved using the combination of above three functions. The set function can be used to convert the values to set, removing duplicates and values function can be used to access the values.

 `# Python3 code to demonstrate``# check for unique values``# Using len() + set() + values()`` ` `# initializing dictionary``test_dict ``=` `{``'Manjeet'` `: ``1``, ``'Akash'` `: ``2``, ``'Akshat'` `: ``3``, ``'Nikhil'` `: ``1``}`` ` `# printing original dictionary``print``(``"The original dictionary : "` `+` `str``(test_dict))`` ` `# using len() + set() + values()``# check for unique values``flag ``=` `len``(test_dict) !``=` `len``(``set``(test_dict.values()))`` ` `# print result``print``(``"Does dictionary contain repetition : "` `+` `str``(flag))`
Output :
```The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up