Write a Python Program to Extract Unique Values Dictionary Values

Given a dictionary containing the key and value pairs,  keys can be unique but values cannot so we have to find unique values present in the dictionary and print it.

In order to  store the unique values we will be using set()  data structure.

 

Write a Python Program to Extract Unique Values Dictionary Values

 

 


Write a Python Program to Extract Unique Values Dictionary Values

Let's take a variable named as fruits and assign the key value pair to it,  assuming the fruits are apple, orange, banana and grapes As shown below  and the values are price of fruit based on the quality type of the fruit (High quality medium quality and low quality fruits).

for example Apple ranges from 200 to 120 based on its quality similarly for the other fruits

fruits = {"apple" : [200, 150, 120],
         "orange" : [200, 130, 50],
         "banana" : [80, 50],
         "grapes" : [120, 80, 50, 40]}



Now let's take a variable named as unique_values and take an empty list.  This list will be used to store all the values present in the above dictionary.

unique_values = list()




Let's iterate all the values present in the dictionary and using the list extend function call we will be adding all the values of the dictionary to the list

The list will store all the values that are duplicate values as well into it.

for value in fruits.values():
   unique_values.extend(value)



Now using the set function call convert the list into a set of values and then using the print function print all the values present in the set this will print unique values present in the dictionary.

print(set(unique_values))



Complete python code
===========================


fruits = {"apple" : [200, 150, 120],
         "orange" : [200, 130, 50],
         "banana" : [80, 50],
         "grapes" : [120, 80, 50, 40]}

unique_values = list()

for value in fruits.values():
   unique_values.extend(value)

print(set(unique_values))





Output
================
{130, 200, 40, 80, 50, 150, 120}




Conclusion
=================
Execute the app of Python program by providing different set of dictionary values,  not down the results

Let me know in the comment section if you have any suggestions to  improve the above Python program.



Post a Comment

0 Comments