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,910 points
733 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,300 points

Related Questions In Python

0 votes
2 answers

Obtaining a value when given a key in python dicionaries

Yes you can check below code dictionary = ...READ MORE

answered Nov 25, 2021 in Python by Suhas
830 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
532 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,230 points
1,087 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,770 points
1,398 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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,441 views
0 votes
1 answer
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,300 points
1,481 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,300 points
2,351 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP