avicohen
avicohen

Reputation: 3047

What is good way to check a key of a dictionary in python?

I have a loop that over some values. I have a dictionary that it's keys are in the values of the loop iteration.

I can't change the outer loop.

for i in range(1, 1000000000000):
    if i in my_dict.keys():
        func()

other_func(i)

Each element in: my_dict.keys() appears in range(1, 1000000000000). However the number of elements in my_dict.keys() is much smaller than the number of iterations.

The problem is that each if check is time consuming. What is a good way of handling this?

Upvotes: 0

Views: 109

Answers (4)

NNNN
NNNN

Reputation: 1

The most simplest way is ,

if my_dict.has_key('key'):

Upvotes: 0

AKS
AKS

Reputation: 19861

I think you can do something like this:

for i in my_dict:
   if 0 < i < 1000000000000:
       func()

range(1, 1000000000000) will generate a list of numbers from 1 to 999999999999 and you just need to check if your key is in that range. So you don't really need to generate the list using range itself.

Upvotes: 9

Hassan Mehmood
Hassan Mehmood

Reputation: 1402

Change your for loop. See below script.

for key in my_dict.keys():
    if 0 < int(key) < 1000000000000:
        func()

Change for loop because in original implementation for loop would iterate at most 1000000000000 times. But now it will iterate maximum of length of my_dict.

Upvotes: 0

Laszlowaty
Laszlowaty

Reputation: 1323

Well, try and except is a good way to go.

for i in range(1, 100000000):
    try:
        my_dict[i]
    except KeyError:
        continue
    func()

If i is not in the keys, then it will throw KeyError and will go to the next iteration. If i is proper key then the func() will be called.

Upvotes: 0

Related Questions