0

How would you get all indexes of the duplicate items as well as the unique items from a list and put it into a dictionary. I want to write a code that doesn’t use the enumerate function and set function as shown below

 x = [1.2, 2.4, 3.1, 4.0, 5.6, 6.5, 1.2, 3.1, 8.1, 23.6, 29.3]

 Dictionary = {}

 for i in set(x):

 if x.count(i) > 1:
   Dictionary[i] = [str(index) for index, value in enumerate(x) if value == i]
 Print(Dictionary)

I hope to get an output as follows:

{1.2:[0,6],2.4:[1],3.1:[2,7]...}
martineau
  • 119,623
  • 25
  • 170
  • 301
Aza
  • 41
  • 4
  • 7
    Why don't you want to use set and enumerate? – mozway Nov 14 '21 at 23:11
  • List= {} declares a dictionary, not a list. – Libra Nov 14 '21 at 23:12
  • https://stackoverflow.com/questions/5419204/index-of-duplicates-items-in-a-python-list ... Note that this is a dictionary, so it might need some adaptations – Larry the Llama Nov 14 '21 at 23:14
  • 2
    Does this answer your question? [Index of duplicates items in a python list](https://stackoverflow.com/questions/5419204/index-of-duplicates-items-in-a-python-list) – Tomerikoo Nov 14 '21 at 23:35
  • You literally just need to wrap the return vale of `list_duplicates` with a `dict` call in the top voted answer in the link above... – Tomerikoo Nov 14 '21 at 23:36

2 Answers2

0

I'm not sure why you'd want to do this, but you certainly can.

x = [1.2, 2.4, 3.1, 4.0, 5.6, 6.5, 1.2, 3.1, 8.1, 23.6, 29.3]

uniqueItems = []
duplicateIndexes = []
counter = 0

for num in x:
    if num not in uniqueItems:
        uniqueItems.append(num)
    else:
        duplicateIndexes.append(counter)
    counter += 1

print(uniqueItems)
print(duplicateIndexes)
Libra
  • 2,544
  • 1
  • 8
  • 24
-1

Using generator expressions and comprehensions this is pretty straightforward.

First let's get all values that appear more than once in a set.

x = [1.2, 2.4, 3.1, 4.0, 5.6, 6.5, 1.2, 3.1, 8.1, 23.6, 29.3]

multiples = set(a for a in set(x) if x.count(a) > 1)

Now, to get the indexes, we can use enumerate and a list comprehension to only collect indexes for values that are in multiples.

[i for i, a in enumerate(x) if a in multiples]

And the output is:

[0, 2, 6, 7]
Chris
  • 26,361
  • 5
  • 21
  • 42