Program to print all distinct elements of a given integer array in Python | Ordered Dictionary


Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted.

Examples:

Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}
Output: 12, 10, 9, 45, 2

Input: arr[] = {1, 2, 3, 4, 5}
Output: 1, 2, 3, 4, 5

Input: arr[] = {1, 1, 1, 1, 1}
Output: 1

This problem has existing solution please refer Print All Distinct Elements of a given integer array link. We will solve this problem in python quickly using Ordered Dictionary. Approach is simple,

  1. Convert array into dictionary data structure using OrderedDict.fromkeys(iterable) function, it converts any iterable into dictionary having elements as Key in the same order they appeared in array.
  2. Now iterate through complete dictionary and print keys.
filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to print All Distinct
# Elements of a given integer array
  
from collections import OrderedDict
  
def printDistinct(input):
     # convert list into ordered dictionary
     ordDict = OrderedDict.fromkeys(input)
  
     # iterate through dictionary and get list of keys
     # list of keys will be resultant distinct elements 
     # in array
     result = [ key for (key, value) in ordDict.items() ]
  
     # concatenate list of elements with ', ' and print
     print (', '.join(map(str, result)))  
  
# Driver program
if __name__ == "__main__":
    input = [12, 10, 9, 45, 2, 10, 10, 45]
    printDistinct(input)

chevron_right


Output:

12, 10, 9, 45, 2


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.