Anshuman Sharma
Anshuman Sharma

Reputation: 15

how to make integer as Key and List as Value in Map in Python?

I have this input

arr = [1,2,1,3,4,2,4,2]

What I'm trying to achieve is make elements of the given list as keys of a map and its indices as values in the form of a list.

Like this :

mp = {1:[0,2],2:[1,5,7],3:[3],4:[4,6]}

And what will be the time-complexity for this?

Upvotes: 0

Views: 1252

Answers (3)

Gijs
Gijs

Reputation: 10891

from collections import defaultdict

result = defaultdict(list)

for pos, num in enumerate(array):
   result[num].append(pos)
   

Time complexity is O(n), there is only one loop and all things in the loop (looking up thing in dictionary, appending an item) are constant wrt. the number of items.

Upvotes: 2

MustA
MustA

Reputation: 1148

arr = [1, 2, 1, 3, 4, 2, 4, 2]
mp = {
    num: [i for i, k in enumerate(arr) if i == num]
    for num in set(arr)
}

or normally:

arr = [1, 2, 1, 3, 4, 2, 4, 2]
mp = {}

for num in set(arr):
    mp[num] = []
    for i, k in enumerate(arr):
        if k == num:
            mp[num] += [i]

Sorry, i do not know much about the time complexities stuff, but naturally two loops, so O(n^2).

Upvotes: 1

user1889297
user1889297

Reputation: 494

try

arr  = [1,2,1,3,4,2,4,2]
d = {}
for n in set(arr):
    d[n] = [i for i, x in enumerate(arr) if x==n]

or

import numpy as np
arr  = [1,2,1,3,4,2,4,2]
arr = np.array(arr)
d = {n:np.where(arr==n)[0].tolist() for n in set(arr)}

Upvotes: 0

Related Questions