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,870 points
45 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
• 13,160 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
30 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
• 4,480 points
10 views
0 votes
1 answer

What is the key difference between self in ruby and self in python?

Ruby and Python are actually very different languages (although ...READ MORE

answered Jul 30 in Python by Mohammad
• 3,060 points
20 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
128 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 216 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
• 13,160 points
467 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
• 13,160 points
233 views