DEV Community

VICTOR OMONDI
VICTOR OMONDI

Posted on

Check if key exists in Dictionary/Object in Python vs Javascript

Python

dict = { 'platform': 'telegram' }

if 'platform' in dict:
 # do something

Javascript

let obj ={ platform: 'telegram' }

if(obj['platform']){

   // do something

}

Discussion (2)

Collapse
lukaszahradnik profile image
Lukáš Zahradník • Edited

The JavaScript version is wrong. The object can contain property that is falsey and you code would evaluate as if the object doesn't contain that property.

The right way would be using in operator, hasOwnProperty method or similar.

if ('platform' in obj) {
  // ...
}

if (obj.hasOwnProperty('platform')) {
  // ...
}
Collapse
waylonwalker profile image
Waylon Walker

❤️ python