473,223 Members | 1,677 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,223 software developers and data experts.

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.numericDict[k][2]
KeyError: 589824 <---- This is the error that is being produced,
because there is no key
589824.

Aug 22 '06 #1
9 6050

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.numericDict[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.numericDict[k][2]
except KeyError, ke:
<do something - report the error to the user? ignore the error?>

Aug 22 '06 #2
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.numericDict[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.numericDict[k][2]
except KeyError:
desc = ''

Aug 22 '06 #3
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.numericDict[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('bar'):
print 'we have it'
else :
print 'we don't have bar.'

That'll do it for me.

Chaz.
Aug 22 '06 #4
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.numericDict[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

Aug 22 '06 #5
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(key,default)

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

Regards,
Pierre

Aug 22 '06 #6
"KraftDiner" <bo*******@yahoo.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.numericDict[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

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

if 'bar' in foo:
# do something

Aug 23 '06 #8
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>

Aug 23 '06 #9
Chaz Ginger <cg********@hotmail.comwrote:
>KraftDiner wrote:
> desc = self.numericDict[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.numericDict[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.numericDict[k] exists
but self.numericDict[k][2] gives a TypeError or IndexError? It
really needs to be:

except KeyError:

--
\S -- si***@chiark.greenend.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
Aug 23 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Tim N. van der Leeuw | last post by:
Hi, I'd like to remove keys from a dictionary, which are not found in a specific set. So it's kind of an intersection-operation. I can create a new dictionary, or a loop over all keys and test...
0
by: Spur | last post by:
Hi all, Suppose I want to implement a dictionary data structure of some kind, say using a simple BST. I'm wondering how to express the basic operations in the nicest manner. Especially the...
2
by: jg | last post by:
I was trying to get custom dictionary class that can store generic or string; So I started with the example given by the visual studio 2005 c# online help for simpledictionay object That seem...
9
by: Paulustrious | last post by:
Is it possible to override the behaviour of a dictionary if an object is not found? string ss=null; Dictionary<string, string> dict = new Dictionary<string, string>(); // method 1 try {...
7
by: Bill Woodruff | last post by:
I've found it's no problem to insert instances of named delegates as values into a generic dictionary of the form : private Dictionary<KeyType, DelegatemyDictionary = new Dictionary<KeyType,...
3
by: craigkenisston | last post by:
I want to use Dictionary class like this: textboxM.Text = oMyDict.GetValue("textboxM"); textboxN.Text = oMyDict.GetValue("textboxN"); Where my dictionary contains the list of values for my...
11
by: John | last post by:
I am coding a radix sort in python and I think that Python's dictionary may be a choice for bucket. The only problem is that dictionary is a mapping without order. But I just found that if the...
0
by: xpding | last post by:
Hello, I have a class MyEmbededList contains a generic dictionary, the value field is actually the MyEmbededList type as well. There is another class need to access and manipulate a list of...
5
by: davenet | last post by:
Hi, I'm new to Python and working on a school assignment. I have setup a dictionary where the keys point to an object. Each object has two member variables. I need to find the smallest value...
18
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I've a question regarding dictionaries. I have an array elements that I created, and I'm trying to sort those elements into various sections. Here's the template of my...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.