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,
- 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.
- Now iterate through complete dictionary and print keys.
# 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) |
Output:
12, 10, 9, 45, 2
Recommended Posts:
- Scraping And Finding Ordered Words In A Dictionary using Python
- Count distinct elements in an array in Python
- Python | Pretty Print a dictionary with dictionary value
- NLP | Storing an ordered dictionary in Redis
- Print anagrams together in Python using List and Dictionary
- Print first n distinct permutations of string using itertools in Python
- Python | Find common elements in three sorted arrays by dictionary intersection
- Python program to create a dictionary from a string
- Python program to find the sum of all items in a dictionary
- Python program to find second maximum value in Dictionary
- Python program to Swap Keys and Values in Dictionary
- Python program to find the highest 3 values in a dictionary
- Python | Minimum number of subsets with distinct elements using Counter
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
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.



