سؤال

Basically this started with my problem that I had when trying to find if the index exist in a dict:

if collection[ key ]: # if exist
    #do this
else: # if no exist
    #do this

But when the index really doesn't exist it throws me a KeyError. So, reading the Python documentation. If the missing() is defined it will not throw the KeyError.

collection = {}
def collection.__missing__():
    return false

The above code on the terminal gives me:

ghelo@ghelo-Ubuntu:~/Music$ python __arrange__.py
  File "__arrange__.py", line 16
    def allArts.__missing__():
               ^
SyntaxError: invalid syntax

So, how to do this correctly? Btw, I'll be needing to use Python 2.7 on this. And is there a difference when running on Python 3?

هل كانت مفيدة؟

المحلول

This is how you do it:

if key in collection:

or, as suggested by @sdolan, you can use the .get method, which returs a default (optional second parameter) if it does not exist.

if collection.get(key, None):

If you want to use __missing__ you would apply it to a class that extends dict (in this case):

class collection(dict):

    def __missing__(self, key):
        print "Too bad, {key} does not exist".format(key=key)
        return None


d = collection()
d[1] = 'one'

print d[1]

if d[2]:
    print "Found it"

OUTPUT

one
Too bad, 2 does not exist

نصائح أخرى

You can check if key exists by handling the KeyError exception using try..except as follows.

try:
    collection[key]
    # do this
except KeyError:
    # do that

This coding style is known as EAFP which means "Easier to ask for forgiveness than permission" http://docs.python.org/glossary.html#term-eafp

Another way would be to use the get method which will by default return None if the key is not found

if collection.get(key) is not None:
    # do this
else:
    # do that

Several answers have already showed what you should probably do in a real situation, but missing can also do what you've asked about.

If you want to use it, you will need to subclass dict.

class mydict(dict):
  def __missing__(self, key):
    return 'go fish'

Then you can create one with:

d = mydict()

And access it with

d[0]
=> 'go fish'
d[0] = 1
d[0]
=> 1

You can use if selection.has_key(keylookingfor).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top