VOOZH about

URL: https://www.geeksforgeeks.org/python/python-unique-value-keys-in-a-dictionary-with-lists-as-values/

⇱ Python - Unique value keys in a dictionary with lists as values - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Unique value keys in a dictionary with lists as values

Last Updated : 27 Apr, 2023

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 discuss certain ways in which this task can be performed. 

Method #1 : Using loop + count() The combination of above functionalities can be used to solve this problem. In this, we perform the task of counting occurrence using count and extraction and testing is done using loop using conditional statement. 

Output : 
The original dictionary is : {'Gfg': [6, 5], 'best': [12, 6, 5], 'is': [6, 10, 5]}
The unique values keys are : ['best', 'is']

Time Complexity: O(n*n)
Auxiliary Space: O(n)

  Method #2 : Using list comprehension + any() + count() The combination of above functions can be used to perform this task. In this, we check for the unique elements using any() and count(). This is one liner way in which this task can be performed. 

Output : 
The original dictionary is : {'Gfg': [6, 5], 'best': [12, 6, 5], 'is': [6, 10, 5]}
The unique values keys are : ['best', 'is']

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #3 : Using Counter function


Output
The original dictionary is : {'Gfg': [6, 5], 'is': [6, 10, 5], 'best': [12, 6, 5]}
The unique values keys are : ['is', 'best']

Method #4: Using operator.countOf() method:


Output
The original dictionary is : {'Gfg': [6, 5], 'is': [6, 10, 5], 'best': [12, 6, 5]}
The unique values keys are : ['is', 'best']

Time Complexity: O(N)

Auxiliary Space: O(N)

Comment
Article Tags: