Python program to get all unique keys from a set of dictionaries

Here, we are going to learn how to get and print all the unique keys present in the set of dictionaries?
Submitted by Shivang Yadav, on March 24, 2021

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

Set is a data-type that does not store duplicates and is unordered.

Key in the dictionary acts like an identifier to the pair. It is always unique.

In this program, we will print all unique keys available in a set of dictionaries.

Example :

Set of dictionary :
[ {"scala":3, "Javascript":3}, {"javaScript":3}, {"C++":3, "Java":3}, {"java":3} ]
List of unique keys :
["scala", "Javascript", "C++", "Java"]

One way to solve the problem is by converting the list of dictionaries to a single list. This is done by storing keys to set and then to list, as set will allow only unique keys. Then we will print the list.

The conversion is done using the chain() method of the itertools library.

  • To create a set and store values, we will use the set() method.
  • To create a list and store values, we will use the list() method.

Program to get all unique keys from a set of dictionaries

# Python program to print list of unique keys 
# from list of Dictionary in Python 

# importing chain() method 
from itertools import chain

# List of Dictionary 
dictList = [ 
        {"Scala":3, "JavaScript":1}, 
        {"C++":9, "Java":0}, 

# Finding list of unique keys 
uniqueKeyList = list(set(chain.from_iterable(value.keys() for value in dictList)))

# Printing the list


['Scala', 'JavaScript', 'Java', 'C++']

Python Dictionary Programs »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.