'Hash Maps/Dictionaries in Python

Came across this leet code.

prevMap = {} #Value:Index
    for i,n in enmuerate(nums):
        diff = target - n
        if diff in prevMap:
            return (prevMap[diff],i)
        prevMap[n] = i                  

This is an extract of the famous Two Sum problem using hashmaps.

I'm new to hashmaps for Python, and hence did not realize that you could look up values directly from the dictionary/hashmap using the 'in' function. However, what I do not understand is the last 2 lines. The second last line is trying to return the index of the value in the hashmap. From what I know in the past, isn't it supposed to be the opposite whereby hashMap[index] = value? Does the opposite work too whereby hashMap[value] = index?

As for the last line, we are trying to put the list nums into the hashmap. In this case, shouldn't it be prevMap[i] = n, since we are trying to map the value n into index i of the hashmap?

Thank you.

hashMap[index] = value? Does the opposite work too whereby hashMap[value] = index?

As for the last line, we are trying to put the list nums into the hashmap. In this case, shouldn't it be prevMap[i] = n, since we are trying to map the value n into index i of the hashmap?

Thank you.



Solution 1:[1]

You are mixing things up. In the second to last line you are returning a tuple of the index within the list stored in the dictionary for one of the values that is part of the two sum and i which is again the index within the list - not the dictionary for the second summand of the two sum. In the last line you store the index within the list for a specific value.

I believe you are mixing up how lists/ dictionaries work. You cannot access dictionaries by index. Just because the syntax is the same with [] does not mean the the way to access values is the same.

l = ["val1", "val2", "val3", "val4"]
d = {
    "key1": "val1",
    "key2": "val2"
}

d_with_keys_defined_as_index = {
    0: "val1",
    1: "val2"
}

# Access first element of list
print(l[0])
# KeyError, a dictionary cannot be accessed by index (except index is explicitly defined as a key)
print(d[0])
# access value by key
print(d["key1"])
# now 0 is explicitly defined as a key, so we can access it using that key. This is still not an access by index though
print(d_with_keys_defined_as_index[0])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1