How to test if a key in a dictionary exists?

F

Frank

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 == 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
 
R

Rune Strand

Yes, you have name.has_key(name_key) and perhaps better, the in
operator:

if name_key in name:
do something
 
J

Jeff McNeil

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.
Alternatively, "exampledict.has_key("a")" is also valid.

See:

http://docs.python.org/tut/node7.html#SECTION007500000000000000000

-Jeff

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 == 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
 
B

Bjoern Schliessmann

Frank said:
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 == 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
 
M

mensanator

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 == 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
 
P

Paul Rubin

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
 
D

Dennis Lee Bieber


Must have been a guest at Furry Night Live, Further Confusion
2007... 15 minute dead gap while the raccoon act got itself together (I
still don't know if the problem was getting some of the act into
dresses, or with the sound man getting the A/V gear working)
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
P

Paul McGuire

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 = 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
 
A

Alex Martelli

Paul McGuire said:
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 = 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
 
J

John Machin

Paul McGuire said:
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 = 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.Traceback (most recent call last):
File said:
histolist = [0] * 10
histolist[3] += 1
histolist [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]

Cheers,
John
 
L

Larry Bates

Frank said:
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 == 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
 
M

mensanator

Paul McGuire said:
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 = 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 said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top