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,890 points
106 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,250 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
120 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, 2019 in Python by Waseem
• 4,540 points
45 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, 2019 in Python by Mohammad
• 3,210 points
147 views
0 votes
1 answer

Adding new column to existing DataFrame in Python pandas

Use the original df1 indexes to create ...READ MORE

answered Dec 23, 2020 in Python by Gitika
• 65,850 points
33 views
0 votes
2 answers
+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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,720 views
0 votes
0 answers
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,250 points
814 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,250 points
993 views