Python Program to get all unique keys from a List of Dictionaries


When it is required to get all the unique keys from a list of dictionary, the dictionary values are iterated over and converted into a set. This is converted to a list and displayed on the console.

Example

Below is a demonstration of the same

my_list = [{'hi' : 11, 'there' : 28}, {'how' : 11, 'are' : 31}, {'you' : 28, 'Will':31}]
print("The list is:")
print(my_list)

my_result = list(set(value for dic in my_list for value in dic.values()))

print("The result is :")
print(my_result)

Output

The list is:
[{'there': 28, 'hi': 11}, {'how': 11, 'are': 31}, {'Will': 31, 'you': 28}]
The result is :
[11, 28, 31]

Explanation

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

  • It is iterated over, and only the ‘values’ of the dictionary are accessed.

  • It is converted to a set to retain only the unique values.

  • This is then converted to a list and assigned to a variable.

  • This is the output that is displayed on the console.

Updated on: 21-Sep-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements