Existing key in Python

0 votes

How do we check if a given key already exists in a dictionary?

I wrote the following code:

if 'key1' in dict.keys():
  print "Hey"
else:
  print "hello"

but this doesn't seem to be the best way to find an existing key. is there any other way?

Oct 3, 2018 in Python by ana1504.k
• 6,630 points
31 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

The intended way to check for the existence of a key in a dictionary is to use in, such as :

d = dict()

for i in xrange(100):
    key = i % 10
    if key in d:
        d[key] += 1
    else:
        d[key] = 1

for a default value you can use dict.get() as such:

d = dict()

for i in xrange(100):
    key = i % 10
    d[key] = d.get(key, 0) + 1
answered Oct 3, 2018 by SDeb
• 10,700 points

Related Questions In Python

0 votes
1 answer

Obtaining a value when given a key in python dicionaries

We cannot. Dictionaries aren't meant to be ...READ MORE

answered May 31, 2018 in Python by Nietzsche's daemon
• 4,260 points
15 views
0 votes
0 answers

how can i contribute to an existing open source project in python?

is there a different platform for this ...READ MORE

May 8 in Python by Waseem
• 2,590 points
5 views
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,670 points
64 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
49 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
54 views
0 votes
1 answer

Key error in Python

A KeyError occurs when the Key doesn't ...READ MORE

answered Sep 20, 2018 in Python by SDeb
• 10,700 points
308 views
0 votes
1 answer

Indentation of Python in Notepad++

To indent the block, select the entire ...READ MORE

answered Sep 18, 2018 in Python by SDeb
• 10,700 points
128 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.