468,268 Members | 1,769 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,268 developers. It's quick & easy.

How to test if a key in a dictionary exists?

Hi,

does anyone know how one can test if, e.g., a dictionary 'name' has a
key called 'name_key'?

This would be possible:

keys_of_names = names.keys()
L = len(keys_of_names)

for i in range(L):
if keys_of_names[i] == name_key:
print 'found'
But certainly not efficient. I would expect there is something like:

name.is_key(name_key)

I appreciate your help!

Frank

Mar 10 '07 #1
11 172834
Frank wrote:
Hi,

does anyone know how one can test if, e.g., a dictionary 'name' has a
key called 'name_key'?
name_key in name

e.g.
>>name={"john": 42}
"john" in name
True
>>"julie" in name
False

--Irmen
Mar 10 '07 #2
Yes, you have name.has_key(name_key) and perhaps better, the in
operator:

if name_key in name:
do something
Mar 10 '07 #3
Sure, you can use "if key in dict" to test for membership:
Python 2.3.5 (#1, Jan 13 2006, 20:13:11)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>exampledict = {"a" : 1, "b" : 2}
"a" in exampledict
True
>>"q" in exampledict
False
>>>
Alternatively, "exampledict.has_key("a")" is also valid.

See:

http://docs.python.org/tut/node7.htm...00000000000000

-Jeff

On 10 Mar 2007 13:17:11 -0800, Frank <su******@gmail.comwrote:
Hi,

does anyone know how one can test if, e.g., a dictionary 'name' has a
key called 'name_key'?

This would be possible:

keys_of_names = names.keys()
L = len(keys_of_names)

for i in range(L):
if keys_of_names[i] == name_key:
print 'found'
But certainly not efficient. I would expect there is something like:

name.is_key(name_key)

I appreciate your help!

Frank

--
http://mail.python.org/mailman/listinfo/python-list
Mar 10 '07 #4
Frank wrote:
does anyone know how one can test if, e.g., a dictionary 'name'
has a key called 'name_key'?
Yes. It's already posted; next time have a look at the concise
library reference:

http://docs.python.org/lib/typesmapping.html
This would be possible:

keys_of_names = names.keys()
L = len(keys_of_names)

for i in range(L):
if keys_of_names[i] == name_key:
print 'found'
Coming in from Java? 8)

Iterating through something using len(X) is quite rare in Python.

If we had no simple "key in dict" test, I'd write the above as:

for key in names.keys():
if key == name_key:
print "found"
break
else:
print "not found"

(It would even suffice to write "for key in names".)

Regards,
Björn

--
BOFH excuse #331:

those damn raccoons!

Mar 11 '07 #5
On Mar 10, 3:17?pm, "Frank" <super...@gmail.comwrote:
Hi,

does anyone know how one can test if, e.g., a dictionary 'name' has a
key called 'name_key'?

This would be possible:

keys_of_names = names.keys()
L = len(keys_of_names)

for i in range(L):
if keys_of_names[i] == name_key:
print 'found'

But certainly not efficient. I would expect there is something like:

name.is_key(name_key)

I appreciate your help!
I often build histograms using dictionaries.

if hist.has_key(outcome):
hist[outcome] += 1 # if key already exists, increment
else:
hist[outcome] = 1 # else create a new key

>
Frank

Mar 11 '07 #6
if hist.has_key(outcome):
hist[outcome] += 1 # if key already exists, increment
else:
hist[outcome] = 1 # else create a new key
You could write that:

hist[outcome] = 1 + hist.get(outcome, 0)

Or with Python 2.5 you could use

hist = defaultdict(int)
...
hist[outcome] += 1 # automatically initializes to 0 if outcome not found
Mar 11 '07 #7
On Mar 10, 9:12 pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
if hist.has_key(outcome):
hist[outcome] += 1 # if key already exists, increment
else:
hist[outcome] = 1 # else create a new key

You could write that:

hist[outcome] = 1 + hist.get(outcome, 0)

Or with Python 2.5 you could use

hist = defaultdict(int)
...
hist[outcome] += 1 # automatically initializes to 0 if outcome not found
Often when building a histogram, one knows in advance what the keys
will be. For instance, when working with data from 0 to 100 and
looking for frequencies by decade, you can initialize the histogram-
dict with:

for i in range(10):
histodict[i] = 0

and then just update the appropriate bucket without having to do any
testing at all:

fibSeqUpTo100 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for val in fibSeqUpTo100:
key = val/10
histodict[ key ] += 1

This has the added benefit of including entries for the empty buckets
as well.

-- Paul

Mar 11 '07 #8
Paul McGuire <pt***@austin.rr.comwrote:
will be. For instance, when working with data from 0 to 100 and
looking for frequencies by decade, you can initialize the histogram-
dict with:

for i in range(10):
histodict[i] = 0
A better way, of course (also saving the histodict = {} which you didn't
mention but surely intended) would be:

histodict = dict.fromkeys(range(10), 0)

In Python, in general, the more conceptually compact, direct, simple and
higher-abstraction approach tends to be faster as well, BTW.
Alex
Mar 12 '07 #9
On Mar 12, 3:19 pm, a...@mac.com (Alex Martelli) wrote:
Paul McGuire <p...@austin.rr.comwrote:
will be. For instance, when working with data from 0 to 100 and
looking for frequencies by decade, you can initialize the histogram-
dict with:
for i in range(10):
histodict[i] = 0

A better way, of course (also saving the histodict = {} which you didn't
mention but surely intended) would be:

histodict = dict.fromkeys(range(10), 0)

In Python, in general, the more conceptually compact, direct, simple and
higher-abstraction approach tends to be faster as well, BTW.
That's so true, especially if it's matched to the problem space, isn't
too new, and doesn't need looking up in the docs :-)

Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license" for more information.
>>histodict = dict.fromkeys(range(10), 0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'dict' is not defined
>>histolist = [0] * 10
histolist[3] += 1
histolist
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
>>>
Cheers,
John

Mar 12 '07 #10
Frank wrote:
Hi,

does anyone know how one can test if, e.g., a dictionary 'name' has a
key called 'name_key'?

This would be possible:

keys_of_names = names.keys()
L = len(keys_of_names)

for i in range(L):
if keys_of_names[i] == name_key:
print 'found'
But certainly not efficient. I would expect there is something like:

name.is_key(name_key)

I appreciate your help!

Frank
Others have posted the direct answer but often you are wanting to
do something with the key if it exists and the best method is:

try: names['name_key']+=1
except KeyError:
#
# Key doesn't exist, create it, display error, or whatever you want
# to do if it doesn't exist.
#

-Larry
Mar 12 '07 #11
On Mar 11, 11:49 pm, "John Machin" <sjmac...@lexicon.netwrote:
On Mar 12, 3:19 pm, a...@mac.com (Alex Martelli) wrote:
Paul McGuire <p...@austin.rr.comwrote:
will be. For instance, when working with data from 0 to 100 and
looking for frequencies by decade, you can initialize the histogram-
dict with:
for i in range(10):
histodict[i] = 0
A better way, of course (also saving the histodict = {} which you didn't
mention but surely intended) would be:
histodict = dict.fromkeys(range(10), 0)
In Python, in general, the more conceptually compact, direct, simple and
higher-abstraction approach tends to be faster as well, BTW.

That's so true, especially if it's matched to the problem space, isn't
too new, and doesn't need looking up in the docs :-)

Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license" for more information.>>histodict = dict.fromkeys(range(10), 0)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'dict' is not defined>>histolist = [0] * 10
>histolist[3] += 1
histolist

[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
In defense of my original if:else: idiom, I'll point
out that there may be more to be done when the key is
absent than simply creating a new one and initializing it.

Also, a dictionary doesn't need an integer index, so I can
create bins such as '2.01','2.02',etc.

And in some cases, it's not known what the range of the
keys will be making it difficult to pre-allocate the list.

And yes, the empty buckets will need to be created for
graphing purposes, but that can be done after the test
has completed so that the only empty buckets that need
be created are those between the outliers.
>
Cheers,
John

Mar 12 '07 #12

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by brianobush | last post: by
2 posts views Thread by VMI | last post: by
2 posts views Thread by jg | last post: by
4 posts views Thread by John Townsend | last post: by
8 posts views Thread by Sweetiecakes | last post: by
reply views Thread by kermitthefrogpy | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.