are there dictionaries in javascript like python?

Learn are there dictionaries in javascript like python? with practical examples, diagrams, and best practices. Covers javascript, python development techniques with visual explanations.

JavaScript Objects: The Equivalent of Python Dictionaries

Hero image for are there dictionaries in javascript like python?

Explore how JavaScript's object and Map types provide similar functionality to Python's dictionaries, covering creation, access, iteration, and common operations.

Developers coming from Python often look for a direct equivalent to its versatile dict (dictionary) type in JavaScript. While JavaScript doesn't have a data structure explicitly named 'dictionary,' its Object type and the more modern Map object serve this purpose effectively. This article will guide you through understanding and utilizing these JavaScript constructs to manage key-value pairs, much like you would with Python dictionaries.

Understanding JavaScript Objects as Dictionaries

In JavaScript, a plain Object is the most common way to store collections of key-value pairs. Keys are typically strings (or Symbols), and values can be any data type. This behavior closely mirrors Python's dictionaries, where keys are unique and map to specific values. Objects are fundamental to JavaScript and are used extensively for data representation.

// Creating a JavaScript object (like a Python dictionary)
const person = {
  name: 'Alice',
  age: 30,
  city: 'New York'
};

// Accessing values
console.log(person.name);    // Output: Alice
console.log(person['age']);  // Output: 30

// Adding or updating values
person.occupation = 'Engineer';
person['age'] = 31;

// Deleting a property
delete person.city;

console.log(person);

Basic operations with JavaScript objects

Introducing the JavaScript Map Object

For scenarios requiring more robust key-value storage, especially when keys might not be strings or when order of insertion matters, JavaScript provides the Map object. Introduced in ES6, Map offers several advantages over plain objects for dictionary-like use cases:

  • Any value as a key: Unlike objects, Map allows keys of any data type (objects, functions, numbers, etc.), not just strings or Symbols.
  • Order of insertion: Map preserves the order of key-value pairs as they were inserted.
  • Performance: For frequent additions and deletions of key-value pairs, Map can offer better performance.
  • Size property: Map has a size property that directly returns the number of key-value pairs, unlike objects where you'd have to iterate or use Object.keys().length.
// Creating a new Map
const myMap = new Map();

// Setting key-value pairs
myMap.set('name', 'Bob');
myMap.set(1, 'One');
const objKey = { id: 1 };
myMap.set(objKey, 'An object as a key');

// Getting values
console.log(myMap.get('name'));    // Output: Bob
console.log(myMap.get(1));         // Output: One
console.log(myMap.get(objKey));    // Output: An object as a key

// Checking for a key
console.log(myMap.has('name'));    // Output: true

// Deleting a key-value pair
myMap.delete(1);

// Getting the size
console.log(myMap.size);           // Output: 2

// Iterating over a Map
for (const [key, value] of myMap) {
  console.log(`${key}: ${value}`);
}

Working with the JavaScript Map object

flowchart TD
    A[Python Dictionary] --> B{Key-Value Storage}
    B --> C[JavaScript Object]
    B --> D[JavaScript Map]

    C --"String/Symbol Keys"--> E[Unordered, Basic Use]
    D --"Any Type Keys"--> F[Ordered, Advanced Use]

    E --"`obj.key` or `obj['key']`"--> G[Access]
    F --"`map.get(key)`"--> G

    G --> H[Data Retrieval]

Conceptual comparison of Python dictionaries, JavaScript objects, and Maps

When to Use Objects vs. Maps

Choosing between a plain Object and a Map depends on your specific needs:

  • Use Object when:

    • You need a simple collection of named data, where keys are known strings at design time (e.g., configuration settings, user profiles).
    • You're using JSON for data exchange, as JSON natively supports objects.
    • You need to access properties frequently using dot notation (obj.property).
    • You're dealing with inheritance and prototypes.
  • Use Map when:

    • You need to store key-value pairs where keys can be non-string data types (e.g., DOM elements, other objects).
    • The order of insertion of elements is important.
    • You frequently add or remove key-value pairs.
    • You need to easily get the size of the collection.
    • You want to avoid potential key collisions with Object's prototype chain.

Python Dictionary

Creating a dictionary

my_dict = { 'name': 'Charlie', 'age': 25, 'is_student': True }

Accessing values

print(my_dict['name'])

Adding/updating

my_dict['city'] = 'London'

Iterating

for key, value in my_dict.items(): print(f"{key}: {value}")

JavaScript Object

// Creating an object const myObject = { name: 'Charlie', age: 25, isStudent: true };

// Accessing values console.log(myObject.name);

// Adding/updating myObject.city = 'London';

// Iterating for (const key in myObject) { if (myObject.hasOwnProperty(key)) { console.log(${key}: ${myObject[key]}); } }

JavaScript Map

// Creating a Map const myMap = new Map([ ['name', 'Charlie'], ['age', 25], ['isStudent', true] ]);

// Accessing values console.log(myMap.get('name'));

// Adding/updating myMap.set('city', 'London');

// Iterating for (const [key, value] of myMap) { console.log(${key}: ${value}); }