Open In App

Python – Extract Unique values dictionary values

Last Updated : 27 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 comprehension + values()

The combination of above functionalities can be used to perform this task. In this, we extract all the values using values() and set comprehension is used to get unique values compiled in list. 

Python3




# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# Using set comprehension + values() + sorted()
 
# initializing dictionary
test_dict = {'gfg': [5, 6, 7, 8],
             'is': [10, 11, 7, 5],
             'best': [6, 12, 10, 8],
             'for': [1, 2, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Extract Unique values dictionary values
# Using set comprehension + values() + sorted()
res = list(sorted({ele for val in test_dict.values() for ele in val}))
 
# printing result
print("The unique values list is : " + str(res))


Output

The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]

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

Extract Unique values dictionary values Using chain() + sorted() + values()

This performs the task in similar way. The difference is that the task of set comprehension is performed using chain(). 

Python3




# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# Using chain() + sorted() + values()
from itertools import chain
 
# initializing dictionary
test_dict = {'gfg': [5, 6, 7, 8],
             'is': [10, 11, 7, 5],
             'best': [6, 12, 10, 8],
             'for': [1, 2, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Extract Unique values dictionary values
# Using chain() + sorted() + values()
res = list(sorted(set(chain(*test_dict.values()))))
 
# printing result
print("The unique values list is : " + str(res))


Output

The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]

The time complexity of the code is O(nlog(n)) where n is the total number of elements in all the lists of the dictionary.

The auxiliary space complexity of the code is O(n) because it creates a new list of all the values in the dictionary using the values() method, which requires O(n) space. 

Extract Unique values dictionary values Using extend() and sort() methods

Python3




# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
            'is' : [10, 11, 7, 5],
            'best' : [6, 12, 10, 8],
            'for' : [1, 2, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
x=list(test_dict.values())
y=[]
res=[]
for i in x:
    y.extend(i)
for i in y:
    if i not in res:
        res.append(i)
res.sort()
 
# printing result
print("The unique values list is : " + str(res))


Output

The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]

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

Extract Unique values dictionary values Using Counter(),append() and sort() methods

  • Import the Counter class from the collections module.
  • Define a dictionary test_dict with string keys and lists of integers as values.
  • Print the original dictionary.
  • Create an empty list called valuesList.
  • Iterate over the dictionary using the items() method to access the keys and values. For each key-value pair, iterate over the values list and append each value to valuesList.
  • Use the Counter() function to count the frequency of each value in valuesList. This creates a dictionary where the keys are the unique values in valuesList and the values are their frequencies.
  • Use the keys() method to extract a list of the unique values from freq.
  • Sort the uniqueValues list in ascending order.
  • Print the final list of unique values

Python3




# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# initializing dictionary
from collections import Counter
test_dict = {'gfg': [5, 6, 7, 8],
             'is': [10, 11, 7, 5],
             'best': [6, 12, 10, 8],
             'for': [1, 2, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
valuesList = []
for key, values in test_dict.items():
    for value in values:
        valuesList.append(value)
freq = Counter(valuesList)
uniqueValues = list(freq.keys())
uniqueValues.sort()
 
# printing result
print("The unique values list is : " + str(uniqueValues))


Output

The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]

The time complexity of the above program is O(nmlog(m)), where n is the number of keys in the dictionary and m is the average number of values per key.

Auxiliary space complexity is O(n*m).

Extract Unique values dictionary values Using Operator.countOf() method

STEPS: 

  1. Import the “operator” module as “op”.
  2. Create a dictionary called “test_dict” and initialize it with some key-value pairs where each key is a string and the value is a list of integers.
  3. Print the original dictionary using the “print()” function.
  4. Create an empty list called “x”.
  5. Get all the values of the dictionary and append them to the list “x” using the “list()” function and the “values()” method of the dictionary.
  6. Create an empty list called “y”.
  7. Iterate over each item in the list “x” using a for loop and append all the elements of each list to the list “y” using the “extend()” method.
  8. Create an empty list called “res”.
  9. Iterate over each item in the list “y” using a for loop.
  10. Check if the count of the current item in the list “res” is zero using the “countOf()” method of the “operator” module.
  11. If the count is zero, append the current item to the list “res” using the “append()” method.
  12. Sort the list “res” using the “sort()” method.
  13. Print the unique values list using the “print()” function.

Python3




# Python3 code to demonstrate working of
# Extract Unique values dictionary values
import operator as op
# initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
            'is' : [10, 11, 7, 5],
            'best' : [6, 12, 10, 8],
            'for' : [1, 2, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
x=list(test_dict.values())
y=[]
res=[]
for i in x:
    y.extend(i)
for i in y:
    if op.countOf(res,i)==0:
        res.append(i)
res.sort()
 
# printing result
print("The unique values list is : " + str(res))


Output

The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]

Auxiliary Space: O(N*N)

Time Complexity:O(N)

Extract Unique values dictionary values Using set() + sum()

Python3




#Python3 code to demonstrate working of
#Extract Unique values dictionary values
#initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
'is' : [10, 11, 7, 5],
'best' : [6, 12, 10, 8],
'for' : [1, 2, 5]}
 
#printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
#Extract Unique values dictionary values
result = list(set(sum(test_dict.values(), [])))
 
#printing result
print("The unique values list is : " + str(result))


Output

The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]

Time complexity: O(n)
Auxiliary Space: O(n)



Similar Reads

Python program to extract the Unique Dictionary Value List elements
Given Dictionary with value lists, extract all unique values. Input : test_dict = {"Gfg" : [6, 7, 4, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 4, 8, 5, 2] Explanation : All distincts elements extracted. Input : test_dict = {"Gfg" : [6, 7, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 8, 5, 2] Explanation : All distincts elements extracted. Method #
6 min read
Ways to extract all dictionary values | Python
While working with Python dictionaries, there can be cases in which we are just concerned about getting the values list and don't care about keys. This is yet another essential utility and solution to it should be known and discussed. Let's perform this task through certain methods. Method #1 : Using loop + keys() The first method that comes to min
3 min read
Python | Extract filtered Dictionary Values
While working with Python dictionaries, there can be cases in which we are just concerned about getting the filtered values list and don’t care about keys. This is yet another essential utility and solution to it should be known and discussed. Let’s perform this task through certain methods. Method #1 : Using loop + keys() The first method that com
4 min read
Python - Extract Dictionary values list to List
Sometimes, while working with dictionary records, we can have problems in which we need to extract all the dictionary values into a single separate list. This can have possible application in data domains and web-development. Lets discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression The combinatio
5 min read
Python - Extract Numerical Dictionary values
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract only if a particular key index is numeric value from the dictionaries which are in form of strings. This can be desired in applications in which we require to do preprocessing. Let's discuss certain ways in which this task can be performed. Input :
5 min read
Python program to extract dictionary items for custom values
Given a dictionary, extract all the items that match given values in the list Example: Input : test_dict = {"Gfg" : 3, "is" : 5, "for" : 8, "Geeks" : 10, "Best" : 16 }, sub_list = [5, 4, 10, 20, 16, 8] Output : {'is': 5, 'Geeks': 10, 'Best': 16, "for" : 8} Explanation : All values matching list values extracted along with keys. Input : test_dict =
4 min read
Extract Dictionary Values as a Python List
The dictionary is a collection of data items in the key-value pair and represented by the braces { }. The list is also a data type used to store the date and represented by the braces [ ]. The built-in Python method items() are used to retrieve all the keys and corresponding values. We can print the dictionary's keys and values by combining the ite
3 min read
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
6 min read
Python | Get Unique values from list of dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the unique values over all the dictionaries in a list. This kind of utility can occur in case while working with similar data and we wish to extract the unique ones. Let's discuss certain ways in which this task can be performed. Method #1 : Using set(
4 min read
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 discuss certain ways in which this task can be pe
4 min read
Practice Tags :