Python | Test if dictionary contains unique keys and values

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.