开发者

Searching for an object

This is how I have been searching for objects in python. Is there any more efficient (faster, simpler) way of doing it?

Obs: A is a known object.

for i in Very_Long_List_Of_Na开发者_C百科mes:
    if A == My_Dictionary[i]:
        print: "The object you are looking for is ", i
        break


The one liner would be: (i for i in List_of_names if A == My_dictionary[i]).next().

This throws a KeyError if there is an item in List_of_names that is not a key in My_dictionary and a StopIteration if the item is not found, else returns the key where it finds A.


I assume you're looking for an object in the values of a Python dictionary.

If you simply want to check for its existence (as in, you don't really care to know which key maps to that value), you can do:

if A in My_Dictionary.values():
    print "The object is in the dictionary"

Otherwise, if you do want to get the key associated with that value:

for k, v in My_Dictionary.iteritems():
    if v == A:
        print "The object you are looking for is ", k
        break

EDIT: Note that you can have multiple keys with the same value in the same dictionary. The above code will only find the first occurence. Still, it sure beats having a huge list of names. :-)


Seems to me like you have you're using the dictionary incorrectly if you're searching through all the keys looking for a specific value.

If A is hashable, then store A in a dictionary with its values as i.

d = {A: 'a_name'}

If My_Dictionary is not huge and can trivially fit in memory, and, A is hashable, then, create a duplicate dictionary from it:

d = dict((value, key) for key, value in My_Dictionary.iteritems())
if A in d:
    print "word you're looking for is: ", d[A]

Otherwise, you'll have to to iterate over every key:

for word, object_ in My_Dictionary.iteritems():
    if object_ == A:
        print "word you're looking for is: ", word
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜