Python.v.JavaScript

JavaScript for Pythonistas. Python for JavaScripters

Dicts / objects

The standard structure to store elements accessible by arbitrary keys (mapping) in Python is called a dict (dictionary) and in JavaScript — object.

Python Javascript
Creation of dictionary / object #
my_dict = {'a': 10, 'b': 20}
my_dict['a']
10
my_dict.a
Exception: AttributeError
'dict' object has no attribute 'a'
var my_obj = {a: 10, b: 20};my_obj['a'];
10
my_obj.a;
10

You can access elements of an object either with square brackets or with dot-notation.


var my_obj = {'long key': 'some value', 
               short_key: 'other value'}my_obj['long key'];
some value
my_obj['short_key'];
other value
my_obj.short_key;
other value
Modification of a value in dictionary / object #
my_dict = {'a': 10, 'b': 20}
my_dict['a'] = 'hello'
my_dict['a']
'hello'
var my_obj = {a: 10, b: 20};
my_obj['a'] = 'hello';my_obj['a'];
hello

var my_obj = {a: 10, b: 20};
my_obj.a = 'hello';my_obj['a'];
hello

Two ways of access (square brackets and dot-notation) gives the same element.

Non-string keys #
my_dict = {}
my_dict[5] = 'hello'
my_dict['5'] = 'world'
my_dict
{5: 'hello', '5': 'world'}
var my_obj = {};
my_obj[5] = 'hello';
my_obj['5'] = 'world';my_obj;
{ '5': 'world' }
my_obj[ ['5'] ];
world

Keys of elements in JavaScript object has to be string. Any other key will be coerced to string.

Check if element with given key exists #
my_dict = {'a': 10, 'b': 20}
'a' in my_dict
True
my_obj = {a: 10, b: 20};'a' in my_obj;
true
Access to non-existent key #
my_dict = {'a': 10, 'b': 20}
my_dict['c']
Exception: KeyError
'c'
my_dict.get('c')
None
my_dict.get('c', 'Nothing')
'Nothing'
my_obj = {'a': 10, 'b': 20};my_obj['c'];
undefined
my_obj.c;
undefined
© Ilya V. Schurov and contributors, 2017
Licenses: CC BY (text), MIT (code).
contribute on github