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.
CodePudding user response:
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)
CodePudding user response:
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]}