Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a key exists in a dictionary? [duplicate]

Tags:

python

Let's say I have an associative array like so: {'key1': 22, 'key2': 42}.

How can I check if key1 exists in the dictionary?

like image 794
aneuryzm Avatar asked Oct 02 '10 10:10

aneuryzm


People also ask

Can a dictionary have duplicate keys?

In this article, we will find out whether a dictionary has duplicate keys or not in Python. The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

How do you check if a key exist in a dictionary?

How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.

Can dictionary contain duplicates?

[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

if key in array:   # do something 

Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.

like image 65
Rafał Rawicki Avatar answered Sep 22 '22 13:09

Rafał Rawicki