Dictionary / Map Visualization

← Back to Non-Linear DS

What is a Dictionary?

A Dictionary (also called Map, Hash Map, or Associative Array) is a collection of key-value pairs where each unique key maps to exactly one value. Dictionaries are implemented using hash tables, providing O(1) average time complexity for insertion, deletion, and lookup operations. They enable fast data retrieval by key rather than by index.

Unlike arrays that use numeric indices, dictionaries allow arbitrary keys (strings, numbers, objects). The key must be unique—adding a value with an existing key updates the previous value. Dictionaries are fundamental for creating efficient lookup tables, caching, counting frequencies, and representing structured data like JSON objects.

Key Characteristics

  • Key-Value Pairs: Each entry consists of a unique key associated with a value
  • Unique Keys: Each key can only appear once; duplicate keys overwrite previous values
  • Fast Access: O(1) average lookup, insertion, and deletion via hash table
  • Dynamic Keys: Keys can be strings, numbers, or other hashable types
  • Unordered: No guaranteed order of entries (unless using ordered variants)
  • Mutable Values: Values can be updated at any time for existing keys
Interactive dictionary simulation. Add key-value pairs, update existing keys, search by key, and manage entries.
Add / Update Entry:
Get Value by Key:
Check Key Exists:
Dictionary Methods:
Load Sample Data:

Dictionary Entries

Size: 0 entries
Dictionary is empty. Add some key-value pairs to get started.

How to Use

Add Entry: Enter a key and value, then click "Set Entry". If key exists, value is updated.

Get Value: Enter a key to retrieve its associated value. Entry will be highlighted.

Has Key: Check if a specific key exists in the dictionary.

Remove Entry: Click "Remove" button on any entry to delete it from the dictionary.

Get All Keys: View all keys currently stored in the dictionary.

Get All Values: View all values currently stored in the dictionary.

Sample Data: Load pre-defined data sets (user profile or country codes) for testing.

Dictionary Operations

Set/Put: Add a new key-value pair or update existing key's value.

Get: Retrieve the value associated with a given key.

Delete/Remove: Remove a key-value pair from the dictionary.

Has/Contains: Check if a key exists in the dictionary.

Keys: Get all keys stored in the dictionary.

Values: Get all values stored in the dictionary.

Dictionary Operations Time Complexity

Set (Insert/Update): O(1) average - Hash function computes index, stores key-value pair.

Get (Lookup): O(1) average - Hash key to find bucket, retrieve value directly.

Delete (Remove): O(1) average - Hash key to locate entry, remove from hash table.

Has (Contains Key): O(1) average - Check if key exists in hash table.

Keys/Values/Entries: O(n) - Must iterate through all entries to collect.

Worst Case: O(n) when many hash collisions occur, but rare with good hash functions.

Space Complexity: O(n) where n is the number of key-value pairs stored.

Real-World Applications

Caching: Store computed results keyed by input parameters for fast retrieval.

Database Indexing: Map primary keys to record locations for O(1) lookups.

Configuration Files: JSON, YAML files storing settings as key-value pairs.

Frequency Counting: Count word occurrences, character frequencies in text analysis.

Phone Books: Map names (keys) to phone numbers (values).

Symbol Tables: Programming language compilers mapping variable names to values/types.

Session Management: Web servers storing user session data by session ID.

DNS Lookup: Domain names (keys) mapped to IP addresses (values).

Translation: Language translation mapping words from one language to another.

Dictionary vs Other Data Structures

vs Array: Dictionaries allow arbitrary keys and O(1) lookup; arrays use numeric indices and O(n) search.

vs Set: Sets only store keys; dictionaries store key-value pairs with associated data.

vs Object (JavaScript): Maps allow any key type; objects convert keys to strings and have prototype pollution risks.

vs Binary Search Tree: Dictionaries have O(1) average vs O(log n); BSTs maintain sorted order.

Ordered Dictionary: Some languages provide ordered dictionaries maintaining insertion order (e.g., Python 3.7+).

Best Use Case: When you need fast lookups by non-numeric keys or want to associate data with identifiers.

Common Dictionary Patterns

Default Values: dict.get(key, default) returns default if key doesn't exist.

Counting Pattern: dict[key] = dict.get(key, 0) + 1 for frequency counting.

Grouping: Map category keys to lists of items belonging to each category.

Memoization: Cache function results using input arguments as keys.

Graph Adjacency List: Map each vertex to its list of neighbors.

Reverse Mapping: Create inverse dictionary swapping keys and values.

// Dictionary (Hash Map) implementation in C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TABLE_SIZE 100

typedef struct Entry {
    char *key;
    char *value;
    struct Entry *next;  // For collision handling
} Entry;

typedef struct {
    Entry *buckets[TABLE_SIZE];
} HashMap;

unsigned int hash(const char *key) {
    unsigned int h = 0;
    while (*key) h = h * 31 + *key++;
    return h % TABLE_SIZE;
}

void put(HashMap *map, const char *key, const char *value) {
    unsigned int idx = hash(key);
    Entry *entry = map->buckets[idx];
    
    // Check if key exists, update value
    while (entry) {
        if (strcmp(entry->key, key) == 0) {
            free(entry->value);
            entry->value = strdup(value);
            return;
        }
        entry = entry->next;
    }
    
    // New entry
    Entry *new_entry = malloc(sizeof(Entry));
    new_entry->key = strdup(key);
    new_entry->value = strdup(value);
    new_entry->next = map->buckets[idx];
    map->buckets[idx] = new_entry;
}

char *get(HashMap *map, const char *key) {
    unsigned int idx = hash(key);
    Entry *entry = map->buckets[idx];
    while (entry) {
        if (strcmp(entry->key, key) == 0) return entry->value;
        entry = entry->next;
    }
    return NULL;  // Key not found
}