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}, 
        {"JavaScript":6}, 
        {"C++":9, "Java":0}, 
        {"Java":2} 
        ]

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

# Printing the list
print(uniqueKeyList)

Output:

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

Python Dictionary Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.