1 min read

Dictionaries and Maps

Dictionaries (also known as Maps, Hash Maps, or Associative Arrays) are data structures that store data in key-value pairs. Unlike arrays which use numeric indices, dictionaries use unique keys to look up values.

1. Concept

  • Key: A unique identifier for the data (e.g., "username", "id", 42).
  • Value: The data associated with the key.

Think of a real-world dictionary: you look up a word (Key) to find its definition (Value).

2. Implementation in Languages

Python (Dictionary)

Python uses the dict type, defined with curly braces {}.

user = {
    "name": "Alice",
    "age": 30,
    "is_admin": True
}

JavaScript (Object & Map)

JavaScript traditionally uses Objects for key-value pairs, but modern JS also has a dedicated Map class.

Object:

let user = {
    name: "Alice",
    age: 30
};

Map:

let inventory = new Map();
inventory.set("apple", 10);
inventory.set("banana", 5);

Java (HashMap)

Java uses the Map interface, commonly implemented by HashMap.

import java.util.HashMap;

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 82);

3. Common Operations

Accessing Values

  • Python: value = data["key"]
  • JavaScript: value = data.key or data["key"] (Object), data.get("key") (Map)
  • Java: value = map.get("key");

Adding/Updating

  • Python: data["new_key"] = "value"
  • JavaScript: data.newKey = "value" (Object), map.set("key", "value") (Map)
  • Java: map.put("key", "value");

programming/common-syntax programming/arrays-and-lists