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
• 7,430 points
33 views

1 answer to this question.

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
• 12,280 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
22 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
• 3,440 points
6 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,810 points
89 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
69 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 128 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
• 12,280 points
362 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
• 12,280 points
164 views