Skizo
Skizo

Reputation: 541

How can I find if key exists in a dictionary?

I want to write a program in python that finds a value in list. Something like this:

arr = [1, 14, 2, 4, 5, 11, 8, 10]
for i in range(1, len(arr)):
    if(i * 2 in arr):
        print "!"

The array I want to check is way way longer so it takes really long time.
i came up with an idea to make a hash table instead of a list. someting like this:

arr = {1: "something", 14: "something", 2: "something", 4: "something",
       5: "something", 11: "something", 8: "something", 10: "something"}

My idea was to check if i for example equal to 2 so to check if arr[i*2] will return something because this way the program won't need to find something just to call it if it exists.

The problem is if i equal to 3 so it will check if arr[3*2] will return something, it won't because there is no key 6 and it will return an error.

How can I do this with my idea?

Upvotes: 2

Views: 6313

Answers (4)

Shashank
Shashank

Reputation: 13869

Your question is actually very confusing because in your first code snippet, you're iterating over the indices of your list, and in the second, you're creating a dictionary with the elements of the list as keys. It's impossible tell what you really want at this point, so here is an answer just in case you were really wanting to check if the index i*2 was valid for any valid index i.

n = len(x)
y = [True]*sum(divmod(n, 2)) + [False]*(n//2)

This code snippet can efficiently create, and assign to y, a list which is a mapping from each valid index of your original list, x, to a boolean value indicating whether (True) or not (False) the index i*2 is less than the length of the array.

Demo:

>>> x = [None] * 3
>>> n = len(x)
>>> y = [True]*sum(divmod(n, 2)) + [False]*(n//2)
>>> y
[True, True, False]
>>> x = [None] * 4
>>> n = len(x)
>>> y = [True]*sum(divmod(n, 2)) + [False]*(n//2)
>>> y
[True, True, False, False]

Upvotes: 0

James Wilson
James Wilson

Reputation: 942

I think the get method for dictionaries is what you want.

If you do arr.get(2) it will return the value you want, or None if there is no value.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239453

Note: The item which you are referring to as arr is actually called list in Python. And the "hash table" is actually called as dictionary. So, I am going to refer the arr object as dict_object.


You can use in operator to check if the key is there in the dictionary or not,

if i * 2 in dict_object:
    print "!"

The in operator will return True if i * 2 is a valid key in the dictionary, False otherwise.


There is one more way to do this. The dictionary objects have a function called get, which accepts a default value to be returned if the key is not found in the dictionary. The default return value is None. You can use None as the sentinel value, like this

if dict_object.get(i * 2) is not None:
    # If the returned value is not None, then the key is present in the dictionary
    print "!"

There is another way to do this. When you access a key which is not there in the dictionary, you will get KeyError. You can except that, like this

for i in range(1, len(dict_object) + 1):
    try:
        if dict_object[i * 2]:
            print "!"
    except KeyError:
         # If value of `i * 2` is not in the dictionary, we will reach here
         pass

Apart from that, if the values you are storing in the dictionary are not used (in other words, if you are worried only about the keys), then you can use set instead of a dictionary, like this

numbers_set = {1, 14, 2, 4, 5, 11, 8, 10}    # Note {..}, not [..]
if i * 2 in numbers_set:
    print "!"

If you already have the list, then you can convert the list to a set, with set function, like this

numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10])
if i * 2 in numbers_set:
    print "!"

PS: There is a bug in your program. In Python, range function runs from the first parameter, till the last parameter value - 1. For example,

>>> range(1, 5)
[1, 2, 3, 4]
>>> range(2, 10)
[2, 3, 4, 5, 6, 7, 8, 9]

the last value will not be included. So, you need to change the range's parameters like this

for i in range(1, len(x) + 1):

Upvotes: 6

marmeladze
marmeladze

Reputation: 6564

I honestly didn't understand what you intend to do, but you have some options.

for your arr dictionary (hash table)

>>> arr
{1: 'something', 2: 'something', 4: 'something', 5: 'something', 8: 'something', 10: 'something', 11: 'something', 14: 'something'}
>>> arr.keys()
[1, 2, 4, 5, 8, 10, 11, 14]

arr.keys() will return keys.

dictionaries also have get(key, message) method, if this dictionary have such key, this method will return its value, else message(default None).

>>> for i in range(len(arr)):
    print arr.get(i*2, "message")



something
something
message
something
something
message
something
message

or printing with keys, to be clearer

>>> for i in range(len(arr)):
    print i, arr.get(i*2)


0 None
1 something
2 something
3 None
4 something
5 something
6 None
7 something

or print message just for existing values

>>> for i in range(len(arr)):
    if i in arr.keys(): print arr.get(i*2)


something
something
something
something

or this.

>>> for i in range(len(arr)):
    if i in arr.keys(): print i,"--->", arr.get(i*2)


1 ---> something
2 ---> something
4 ---> something
5 ---> something

Upvotes: 0

Related Questions