Python | Test if dictionary contains unique keys and values
Last Updated :
22 Mar, 2023
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
# 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))
OutputThe original dictionary : {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
Does dictionary contain repetition : True
Time Complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary Space: O(n), where n is the number of elements in the dictionary, as we are storing all the values in the hash_val dictionary.
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
# 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))
OutputThe original dictionary : {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
Does dictionary contain repetition : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using values() and count() method
Python3
# Python3 code to demonstrate
# check for unique values
# 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
x = list(test_dict.values())
for i in x:
if x.count(i) > 1:
flag = True
break
# print result
print("Does dictionary contain repetition : " + str(flag))
OutputThe original dictionary : {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
Does dictionary contain repetition : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using Counter() function
Python3
# Python3 code to demonstrate
# check for unique values
from collections import Counter
# initializing dictionary
test_dict = {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
flag = True
freqKeys = Counter(list(test_dict.keys()))
freqValues = Counter(list(test_dict.values()))
if(freqKeys == len(test_dict) and freqValues == len(test_dict)):
flag = False
# print result
print("Does dictionary contain repetition : " + str(flag))
OutputThe original dictionary : {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
Does dictionary contain repetition : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 5: using operator.countOf() method
Python3
# Python3 code to demonstrate
# check for unique values
import operator as op
# 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
x = list(test_dict.values())
for i in x:
if op.countOf(x, i) > 1:
flag = True
break
# print result
print("Does dictionary contain repetition : " + str(flag))
OutputThe original dictionary : {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
Does dictionary contain repetition : True
Time Complexity: O(N)
Auxiliary Space : O(1)
Method 6: Using set() function
In this method, we create a set of the values of the dictionary using the set() function, which only contains unique elements. We compare the length of this set with the length of the original dictionary. If they are equal, it means that all the values in the dictionary are unique.
Python3
# Python3 code to demonstrate
# check for unique values
# initializing dictionary
test_dict = {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# check for unique values
flag = len(test_dict) == len(set(test_dict.values()))
# print result
print("Does dictionary contain repetition : " + str(not flag))
OutputThe original dictionary : {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
Does dictionary contain repetition : True
The time complexity of the given code is O(n), where n is the number of key-value pairs in the dictionary.
The auxiliary space used by the code is O(n), where n is the number of key-value pairs in the dictionary.
Method 7: Using the lambda function and map():
Algorithm:
- Initialize a dictionary test_dict with key-value pairs.
- Using lambda function and map(), extract all the values from the dictionary and convert them into a list.
- Use set() to extract unique values from the list.
- Check if the length of the original list and the set are equal or not. If they are not equal, then the dictionary contains repetitions.
- Print the result.
Python3
# check for unique values
# initializing dictionary
test_dict = {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
flag = len(list(map(lambda x: x, test_dict.values()))) != len(set(test_dict.values()))
# print result
print("Does dictionary contain repetition : " + str(flag))
#This code is contributed by Jyothi Pinjala.
OutputThe original dictionary : {'Manjeet': 1, 'Akash': 2, 'Akshat': 3, 'Nikhil': 1}
Does dictionary contain repetition : True
Time complexity: O(n), where n is the number of values in the dictionary.
Space complexity: O(n), where n is the number of values in the dictionary (for the list created using map() function).has context menu
Similar Reads
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets
4 min read
Check If Dictionary Value Contains Certain String with Python
We need to check if the value associated with a key in a dictionary contains a specific substring. For example, if we have a dictionary of user profiles and we want to check if any userâs description contains a particular word, we can do this easily using various methods. Letâs look at a few ways to
4 min read
How to Add Same Key Value in Dictionary Python
Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python.Adding
2 min read
Python - Keys associated with Values in Dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to reform the dictionary, in the form in which all the values point to the keys that they belong to. This kind of problem can occur in many domains including web development and data domains. Lets discuss certain
5 min read
Get Unique Values from a List in Python
Getting unique values from a list in Python allows you to remove duplicates and work with distinct elements. For example, given the list a = [1, 2, 1, 1, 3, 4, 3, 3, 5], you might want to extract the unique values [1, 2, 3, 4, 5]. There are various efficient methods to extract unique values from a l
3 min read
Python - Counter.items(), Counter.keys() and Counter.values()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Pythonâs general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-cl
3 min read
Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a ke
5 min read
Python - Keys associated with value list in dictionary
Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in P
4 min read
How to use a List as a key of a Dictionary in Python 3?
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained
3 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value c
5 min read