python - How can I find if key exists in a dictionary? -
i want write program in python finds value in list. this:
arr = [1, 14, 2, 4, 5, 11, 8, 10] in range(1, len(arr)): if(i * 2 in arr): print "!" the array want check way way longer takes long time.
came idea make hash table instead of list. someting this:
arr = {1: "something", 14: "something", 2: "something", 4: "something", 5: "something", 11: "something", 8: "something", 10: "something"} my idea check if i example equal 2 check if arr[i*2] return because way program won't need find call if exists.
the problem if i equal 3 check if arr[3*2] return something, won't because there no key 6 , return error.
how can idea?
note: item referring arr called list in python. , "hash table" called dictionary. so, going refer arr object dict_object.
you can use in operator check if key there in dictionary or not,
if * 2 in dict_object: print "!" the in operator return true if i * 2 valid key in dictionary, false otherwise.
there 1 more way this. dictionary objects have function called get, accepts default value returned if key not found in dictionary. default return value none. can use none sentinel value, this
if dict_object.get(i * 2) not none: # if returned value not none, key present in dictionary print "!" there way this. when access key not there in dictionary, keyerror. can except that, this
for in range(1, len(dict_object) + 1): try: if dict_object[i * 2]: print "!" except keyerror: # if value of `i * 2` not in dictionary, reach here pass apart that, if values storing in dictionary not used (in other words, if worried keys), can use set instead of dictionary, this
numbers_set = {1, 14, 2, 4, 5, 11, 8, 10} # note {..}, not [..] if * 2 in numbers_set: print "!" if have list, can convert list set, set function, this
numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10]) if * 2 in numbers_set: print "!" ps: there bug in program. in python, range function runs first parameter, till last parameter value - 1. example,
>>> range(1, 5) [1, 2, 3, 4] >>> range(2, 10) [2, 3, 4, 5, 6, 7, 8, 9] the last value not included. so, need change range's parameters this
for in range(1, len(x) + 1):
Comments
Post a Comment