Q:

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

belongs to collection: Python Dictionary Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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++']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to extract unique values from the d... >>
<< Python program to randomize (shuffle) values of di...