Python – Dictionaries with Unique Value Lists



When it is required to get the dictionaries with unique value lists, the ‘set’ operator and the list methods are used, along with a simple iteration.

Example

Below is a demonstration of the same −

my_dictionary = [{'Python' : 11, 'is' : 22}, {'fun' : 11, 'to' : 33}, {'learn' : 22},{'object':9},{'oriented':11}] print("The dictionary is : " ) print(my_dictionary) my_result = list(set(value for element in my_dictionary for value in element.values())) print("The resultant list is : ") print(my_result) print("The resultant list after sorting is : ") my_result.sort() print(my_result)

Output

The dictionary is : [{'Python': 11, 'is': 22}, {'fun': 11, 'to': 33}, {'learn': 22}, {'object': 9}, {'oriented': 11}] The resultant list is : [33, 11, 22, 9] The resultant list after sorting is : [9, 11, 22, 33]

Explanation

  • A list of dictionary is defined and is displayed on the console.

  • The values in the dictionary are accessed by iterating over, and converted to a set.

  • This way, the unique elements are obtained.

  • It is then converted to a list, and assigned to a variable.

  • It is displayed as the output on the console.

  • It is again sorted and displayed on the console.

Updated on: 2021-09-13T11:51:39+05:30

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements