Open In App

Python – Key with maximum unique values

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary with a values list, extract the key whose value has the most unique values.

Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]} 
Output : "Gfg" 
Explanation : "Gfg" having max unique elements i.e 5. 
Input : test_dict = {"Gfg" : [5, 7, 7, 7, 7], "is" : [6, 7, 7, 7], "Best" : [9, 9, 6, 5, 5]} 
Output : "Best" 
Explanation : 3 (max) unique elements, 9, 6, 5 of "Best".

Method #1: Using loop

This is a brute way in which this task can be performed. In this, we iterate for all the list values and check for each key’s value count, extracting the key with maximum unique values.

Python3




# Python3 code to demonstrate working of
# Key with maximum unique values
# Using loop
 
# initializing dictionary
test_dict = {"Gfg": [5, 7, 5, 4, 5],
             "is": [6, 7, 4, 3, 3],
             "Best": [9, 9, 6, 5, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
max_val = 0
max_key = None
 
for sub in test_dict:
 
    # Testing for length using len() method and
    # converted to set for duplicates removal
    if len(set(test_dict[sub])) > max_val:
        max_val = len(set(test_dict[sub]))
        max_key = sub
 
# Printing result
print("Key with maximum unique values : " + str(max_key))


Output

The original dictionary is : {‘Gfg’: [5, 7, 5, 4, 5], ‘is’: [6, 7, 4, 3, 3], ‘Best’: [9, 9, 6, 5, 5]} Key with maximum unique values : is

Time complexity: O(n*k*log k), where n is the number of keys in the dictionary and k is the length of the largest list among all the lists in the dictionary. This is because the program iterates through each key in the dictionary, and for each key, it first creates a set from the list associated with that key (which takes O(k) time) and then finds the length of the set (which takes O(klog k) time due to the sorting operation in the set). Therefore, the total time complexity is O(nk*log k).
Auxiliary space: O(k), because the program creates a set for each list in the dictionary, and the size of each set can be at most k (if all the elements in the list are distinct).

Method #2: Using sorted() + lambda() + set() + values() + len()

The combination of the above functions can be used to solve this problem. In this, we reverse sort the dictionary keys on basis of set length and return the first result.

Python3




# Python3 code to demonstrate working of
# Key with maximum unique values
# Using sorted() + lambda() + set() + values() + len()
 
# Initializing dictionary
test_dict = {"Gfg" : [5, 7, 5, 4, 5],
             "is" : [6, 7, 4, 3, 3],
             "Best" : [9, 9, 6, 5, 5]}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Sorting to reverse sort dictionary
max_key = sorted(test_dict, key = lambda ele: len(
          set(test_dict[ele])), reverse = True)[0]
 
# Printing result
print("Key with maximum unique values : " + str(max_key))


Output

The original dictionary is : {‘Gfg’: [5, 7, 5, 4, 5], ‘is’: [6, 7, 4, 3, 3], ‘Best’: [9, 9, 6, 5, 5]} Key with maximum unique values : is

Time complexity: O(NlogN), where N is the number of keys in the dictionary.
Auxiliary space: O(N), where N is the number of keys in the dictionary. 

Method #3:Using Counter() method

Python3




# Python3 code to demonstrate working of
# Key with maximum unique values
from collections import Counter
 
# initializing dictionary
test_dict = {"Gfg": [5, 7, 5, 4, 5],
             "is": [6, 7, 4, 3, 3],
             "Best": [9, 9, 6, 5, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
max_val = 0
max_key = None
 
for sub in test_dict:
 
    # test for length using len()
    # converted to Counter() to calculcate the unique values
        # (for duplicates removal)
    if len(Counter(test_dict[sub])) > max_val:
        max_val = len(set(test_dict[sub]))
        max_key = sub
 
# printing result
print("Key with maximum unique values : " + str(max_key))


Output

The original dictionary is : {'Gfg': [5, 7, 5, 4, 5], 'is': [6, 7, 4, 3, 3], 'Best': [9, 9, 6, 5, 5]}
Key with maximum unique values : is

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

Method #4: Using  a list comprehension:

Algorithm:

  1. Initialize a dictionary named “test_dict” with keys “Gfg”, “is”, and “Best”, and corresponding values as lists of integers.
  2. Print the original dictionary.
  3. Use a list comprehension to create a list of tuples “unique_counts”, where each tuple contains a key-value pair
  4. from the dictionary and the number of unique values in the corresponding list.
  5. Use the max() function with a key argument to find the tuple with the maximum unique value.
  6. Extract the key from the tuple with the maximum unique value.
  7. Print the key with the maximum unique value.

Python3




# Initializing dictionary
test_dict = {"Gfg": [5, 7, 5, 4, 5],
             "is": [6, 7, 4, 3, 3],
             "Best": [9, 9, 6, 5, 5]}
 
# Printing the original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Creating a list of tuples
# where each tuple contains the key and
# the number of unique values
# using list comprehension
unique_counts = [(key, len(set(values))) for key, values in test_dict.items()]
 
# Finding the key with the maximum unique values
# using the max() function with a key argument
max_key = max(unique_counts, key=lambda x: x[1])[0]
 
# Printing the result
print("Key with maximum unique values : " + str(max_key))
 
# This code is contributed by Rayudu


Output

The original dictionary is : {'Gfg': [5, 7, 5, 4, 5], 'is': [6, 7, 4, 3, 3], 'Best': [9, 9, 6, 5, 5]}
Key with maximum unique values : is

Time complexity: O(n), where n is the total number of values in the dictionary. This is because we need to iterate over all the values in the dictionary to compute the number of unique values for each key.
Auxiliary Space: O(n), where n is the total number of values in the dictionary. This is because we need to store all the key-value pairs in the dictionary as well as the list of tuples “unique_counts”.

Method #5: Using defaultdict and set

  1. Import defaultdict from the collections module.
  2. Create an empty defaultdict with the default value set to an empty set.
  3. Loop through the values in the dictionary.
  4. For each value, loop through the elements in the list and add them to the set for the corresponding key in the defaultdict.
  5. Loop through the keys in the dictionary and find the key with the maximum length of the set of unique values.
  6. Print the result.

Python3




from collections import defaultdict
 
# Initializing dictionary
test_dict = {"Gfg": [5, 7, 5, 4, 5],
             "is": [6, 7, 4, 3, 3],
             "Best": [9, 9, 6, 5, 5]}
 
# Creating defaultdict with default value set to an empty set
unique_vals = defaultdict(set)
 
# Looping through values and add elements to sets in defaultdict
for key, value in test_dict.items():
 
    # Iterating element in value
    for elem in value:
        unique_vals[key].add(elem)
 
# Finding key with maximum length of unique values
max_key = max(unique_vals, key=lambda x: len(unique_vals[x]))
 
# Printing the result
print("Key with maximum unique values : " + str(max_key))


Output

Key with maximum unique values : is

Time complexity: O(nm), where n is the number of keys in the dictionary and m is the maximum length of the lists in the dictionary.
Auxiliary space: O(nm), where n is the number of keys in the dictionary and m is the maximum length of the lists in the dictionary.

Method #6: Using dictionary comprehension and set

Stepwise Approach:

  1. Initialize a dictionary comprehension that iterates over the key-value pairs of the original dictionary.
  2. For each key-value pair, create a new key-value pair where the key is the original key, and the value is a set of the unique elements in the original value list.
  3. Use the max() function with a key argument to find the key with the maximum number of unique elements in its corresponding value set.
  4. Print the result.

Python3




# Initializing dictionary
test_dict = {"Gfg": [5, 7, 5, 4, 5],
             "is": [6, 7, 4, 3, 3],
             "Best": [9, 9, 6, 5, 5]}
 
# Printing the original dictionary
print("The original dictionary is : " + str(test_dict))
 
# create a dictionary where each key is the original key,
# and each value is a set of the unique elements in the original value list
# using a dictionary comprehension
unique_dict = {key: set(values) for key, values in test_dict.items()}
 
# using the max() function with a key argument to
# find the key with the maximum number of unique elements in its corresponding value set
max_key = max(unique_dict, key=lambda x: len(unique_dict[x]))
 
# Printing the result
print("Key with maximum unique values : " + str(max_key))


Output

The original dictionary is : {'Gfg': [5, 7, 5, 4, 5], 'is': [6, 7, 4, 3, 3], 'Best': [9, 9, 6, 5, 5]}
Key with maximum unique values : is

Time complexity: O(n logn) due to the use of the max() function with a key argument, which requires sorting.
Auxiliary space: O(n) due to the creation of a new dictionary.



Similar Reads

Python - Unique Values of Key in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the unique values of a particular key in Dictionary List. This kind of problem in very common in day-day programming and web development domain. Let us discuss certain ways in which this task can be performed. Input : test_list = [{'geeks': 10, 'for
7 min read
Python - Unique values count of each Key
Given a Dictionaries list, the task is to write a Python program to count the unique values of each key. Example: Input : test_list = [{"gfg" : 1, "is" : 3, "best": 2}, {"gfg" : 1, "is" : 3, "best" : 6}, {"gfg" : 7, "is" : 3, "best" : 10}] Output : {'gfg': 2, 'is': 1, 'best': 3} Explanation : gfg has 1 and 7 as unique elements, hence 2.Input : test
7 min read
Python - Extract target key from other key values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract particular key on basis of other matching record keys when there is exact match. Lets discuss certain ways in which this task can be performed. Method #1: Using loop + conditions This is one of the ways in which this task can be performed. In this,
11 min read
Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python - Extract values of Particular Key in Nested Values
Given a dictionary with nested dictionaries as values, extract all the values with of particular key. Input : test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12}, 'is' : {"a" : 15, "b" : 19, "c" : 20}, 'best' :{"a" : 5, "b" : 10, "c" : 2}}, temp = "b" Output : [9, 10, 19] Explanation : All values of "b" key are extracted. Input : test_dict = {'Gfg' :
4 min read
Python | Tuples with maximum key of similar values
Sometimes, while working with Python, we can have a problem in which we need to get all the records. This data can have similar values and we need to find maximum key-value pair. This kind of problem can occur while working with data. Let's discuss certain ways in which this task can be done. Method #1: Using max() + groupby() + itemgetter() + list
6 min read
Python - Extract Unique value key pairs
Sometimes, while working on Python dictionaries, we can have a problem in which we need to perform the extraction of selected pairs of keys from dictionary list, that too unique. This kind of problem can have application in many domains including day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list
5 min read
Python - Filter key's value from other key
Sometimes, while working with Python dictionary, we can have a problem in which we need to extract a value from dictionary list of the key on basis of some other key equality. This kind of problem is common in domains that include data, for e.g web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [{'g
7 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
three90RightbarBannerImg