'Is there a way to get key of dictionary without iterating it over?
I have a code like this. And dictionary like this {0: 2, 1: 7, 2: 11, 3: 15}. I am trying to implement hash table using dictionary for array arr=[2,7,11,15]. 2 is stored at index 0, 7 at index 1 and so on.
arr=[2,7,11,15]
target=9
hashmap = {}
for i in range(len(arr)):
hashmap[i]=arr[i]
for i in range(len(arr)):
num=arr[i]
remaining=target-num
if(hashmap.get(remaining)):
index=hashmap.index(remaining)
print(index)
I want index of 7 i.e., '1'. Can I do it Without iterating over dictionary inside the outer loop at line 6?
Solution 1:[1]
If it's just about getting them enumerated, you could use enumerate for that task. For example: enumerate([2,7,11,15]) would give you an iterator, that you can loop over:
for i, j in enumerate([2,7,11,15]):
[Do stuff with i and j]
or if you want it in the form of a dictionary or list you can cast that iterator in that form using dict(enumerate([2,7,11,15])).
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 |
