key not found in dictionary

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • KraftDiner

    key not found in dictionary

    I have a dictionary and sometime the lookup fails...
    it seems to raise an exception when this happens.
    What should I do to fix/catch this problem?

    desc = self.numericDic t[k][2]
    KeyError: 589824 <---- This is the error that is being produced,
    because there is no key
    589824.

  • hiaips

    #2
    Re: key not found in dictionary


    KraftDiner wrote:
    I have a dictionary and sometime the lookup fails...
    it seems to raise an exception when this happens.
    What should I do to fix/catch this problem?
    >
    desc = self.numericDic t[k][2]
    KeyError: 589824 <---- This is the error that is being produced,
    because there is no key
    589824.
    It raises a KeyError, as you are seeing. Just use a try/except
    construction and handle the error as required by your application:

    try:
    desc = self.numericDic t[k][2]
    except KeyError, ke:
    <do something - report the error to the user? ignore the error?>

    Comment

    • linnorm@gmail.com

      #3
      Re: key not found in dictionary

      KraftDiner wrote:
      I have a dictionary and sometime the lookup fails...
      it seems to raise an exception when this happens.
      What should I do to fix/catch this problem?
      >
      desc = self.numericDic t[k][2]
      KeyError: 589824 <---- This is the error that is being produced,
      because there is no key
      589824.
      Given the information provided the simplest answer would be:

      try:
      desc = self.numericDic t[k][2]
      except KeyError:
      desc = ''

      Comment

      • Chaz Ginger

        #4
        Re: key not found in dictionary

        KraftDiner wrote:
        I have a dictionary and sometime the lookup fails...
        it seems to raise an exception when this happens.
        What should I do to fix/catch this problem?
        >
        desc = self.numericDic t[k][2]
        KeyError: 589824 <---- This is the error that is being produced,
        because there is no key
        589824.
        >
        As stated you can wrap the access in the try - except - else statement,
        as in

        try:
        foo['bar']
        except :
        # Handle the error.
        pass
        else :
        # We have it, so use it...
        print foo['bar']

        Or you can use the has_key() and test it first. For example

        if foo.has_key('ba r'):
        print 'we have it'
        else :
        print 'we don't have bar.'

        That'll do it for me.

        Chaz.

        Comment

        • Philippe Martin

          #5
          Re: key not found in dictionary

          KraftDiner wrote:
          I have a dictionary and sometime the lookup fails...
          it seems to raise an exception when this happens.
          What should I do to fix/catch this problem?
          >
          desc = self.numericDic t[k][2]
          KeyError: 589824 <---- This is the error that is being produced,
          because there is no key
          589824.
          If you agree that the key is not there, then just catch the exception
          (try ... except)

          Philippe

          Comment

          • Pierre Quentel

            #6
            Re: key not found in dictionary

            Depending on what you want to do if the key doesn't exist, you might
            want to use the dictionary method get() :

            value = some_dict.get(k ey,default)

            sets value to some_dict[key] if the key exists, and to default
            otherwise

            Regards,
            Pierre

            Comment

            • Ben Finney

              #7
              Re: key not found in dictionary

              "KraftDiner " <bobrien18@yaho o.comwrites:
              I have a dictionary and sometime the lookup fails...
              it seems to raise an exception when this happens.
              What should I do to fix/catch this problem?
              >
              desc = self.numericDic t[k][2]
              KeyError: 589824 <---- This is the error that is being produced,
              because there is no key
              589824.
              Others have suggested the general solution of using 'try ... except
              Foo' for catching a particular exception and dealing with it.

              In the specific use case of wanting a default value when a dictionary
              doesn't have a particular key, you can also use this:
              >>foo = {0: "spam", 1: "eggs", 7: "beans"}
              >>for key in [1, 2, 7]:
              ... desc = foo.get(key, None)
              ... print repr(desc)
              ...
              'eggs'
              None
              'beans'

              A brief description is at 'help(dict.get) '.

              --
              \ "The illiterate of the future will not be the person who cannot |
              `\ read. It will be the person who does not know how to learn." |
              _o__) -- Alvin Toffler |
              Ben Finney

              Comment

              • Simon Forman

                #8
                Re: key not found in dictionary

                Or you can use the has_key() and test it first. For example
                >
                if foo.has_key('ba r'):
                print 'we have it'
                else :
                print 'we don't have bar.'
                >
                Nowadays you can also say:

                if 'bar' in foo:
                # do something

                Comment

                • Fredrik Lundh

                  #9
                  Re: key not found in dictionary

                  Ben Finney wrote:
                  In the specific use case of wanting a default value when a dictionary
                  doesn't have a particular key, you can also use this:
                  >
                  >>foo = {0: "spam", 1: "eggs", 7: "beans"}
                  >>for key in [1, 2, 7]:
                  ... desc = foo.get(key, None)
                  usually spelled

                  desc = foo.get(key) # returns None if not present

                  or

                  desc = foo.get(key, default)

                  if you want something other than None.

                  </F>

                  Comment

                  • Sion Arrowsmith

                    #10
                    Re: key not found in dictionary

                    Chaz Ginger <cginboston@hot mail.comwrote:
                    >KraftDiner wrote:
                    > desc = self.numericDic t[k][2]
                    >KeyError: 589824 <---- This is the error that is being produced,
                    >As stated you can wrap the access in the try - except - else statement,
                    >as in
                    >
                    >try:
                    foo['bar']
                    >except :
                    # Handle the error.
                    Bare "except" is generally a bad idea. Here, it could be letting
                    through whole truckloads of other errors. Suppose the OP typos:

                    try:
                    desc = self.numericDic t[j][2]
                    except:
                    # handle missing key

                    but the except isn't handling a KeyError, it's got a NameError
                    (assuming j doesn't exist). Or what if self.numericDic t[k] exists
                    but self.numericDic t[k][2] gives a TypeError or IndexError? It
                    really needs to be:

                    except KeyError:

                    --
                    \S -- siona@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
                    ___ | "Frankly I have no feelings towards penguins one way or the other"
                    \X/ | -- Arthur C. Clarke
                    her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

                    Comment

                    Working...