Cant get my python dictionary to work properly

nums = [3,2,2,3]

hash = {}
        
for i in range(len(nums)):
    if nums[i] not in hash:
        hash[nums[i]] = [i]
    else:
        hash[nums[i]] = hash[nums[i]].append(i)
        
print(hash)

What im trying to do here is add the indexes of occurrences of a certain element in a list as a list as a value to the key, which is the element itself.

For Example:-
nums = [3,2,2,3]
should return {3: [0,3], 2: [1,2]
instead, what my code returns is this:-
{2: None, 3: None}

Please tell me where I’m going wrong in my code. Thanks.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

hash[nums[i]] = hash[nums[i]].append(i)

append always returns none as it modifies the original list you instead need to do just

hash[nums[i]].append(i)

there everything else is fine.
Also you can use the built in enumerate function instead of your for loop

nums = [3,2,2,3]

hash = {}
        
for i, item in enumerate(nums):
    if item not in hash:
        hash[item] = [i]
    else:
        hash[item].append(i)
        
print(hash)

Method 2

as juanpa.arrivillaga already commented, you should not overwrite your hash dict when appending to its values.

nums = [3, 2, 2, 3]

hash = {}
for i in range(len(nums)):
    if nums[i] not in hash:
        hash[nums[i]] = [i]
    else:
        hash[nums[i]].append(i)

print(hash)
# {3: [0, 3], 2: [1, 2]}

a slightly more compact approach using enumerate und setdefault gives you the same results.

hash = {}
nums = [3, 2, 2, 3]
for i, num in enumerate(nums):
    hash.setdefault(num, []).append(i)

print(hash)
# {3: [0, 3], 2: [1, 2]}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x