Dictionaries and Maps compared across 16 programming languages

Key-value collections: dictionaries, maps, and hashes.

Python JavaScript TypeScript Java C C++ C# Go Rust PHP Ruby Swift Kotlin SQL Bash HTML & CSS

PyPython

person = {"name": "Ada", "alter": 36}
person["stadt"] = "London"
for schluessel, wert in person.items():
    print(schluessel, "=", wert)
print(person.get("email", "no email"))

get returns a default value instead of an error when the key is missing.

JSJavaScript

const person = { name: "Ada", alter: 36 };
person.stadt = "London";
for (const [schluessel, wert] of Object.entries(person)) {
  console.log(schluessel, "=", wert);
}
console.log(person.email ?? "no email");

Objects serve as dictionaries; Object.entries returns the pairs. For arbitrary key types there is also the Map class. ?? returns a default value for undefined.

TSTypeScript

const person: Record<string, string | number> = { name: "Ada", alter: 36 };
person.stadt = "London";
for (const [schluessel, wert] of Object.entries(person)) {
  console.log(schluessel, "=", wert);
}
console.log(person.email ?? "no email");

Record<string, ...> describes an object with arbitrary keys. With noUncheckedIndexedAccess, person.email is typed as possibly undefined – which fits ??. For keys of any type there is Map<K, V>.

JvJava

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Object> person = new LinkedHashMap<>();
        person.put("name", "Ada");
        person.put("alter", 36);
        person.put("stadt", "London");
        for (var e : person.entrySet()) {
            System.out.println(e.getKey() + " = " + e.getValue());
        }
        System.out.println(person.getOrDefault("email", "no email"));
    }
}

LinkedHashMap keeps the insertion order. getOrDefault returns a fallback value instead of null if the key is missing.

CC

#include <stdio.h>
#include <string.h>

struct Eintrag { const char *key; int wert; };

int main(void) {
    struct Eintrag map[] = {{"red", 1}, {"green", 2}, {"blue", 3}};
    const char *gesucht = "green";
    for (size_t i = 0; i < sizeof map / sizeof map[0]; i++) {
        if (strcmp(map[i].key, gesucht) == 0) {
            printf("%s -> %d\n", gesucht, map[i].wert);
        }
    }
    return 0;
}

C has no built-in map. For a few entries, an array of structs with linear search is enough; for many, you build a hash table or use a library (e.g. uthash).

C++C++

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> person{{"Ada", 36}, {"Bob", 25}};
    person["Cy"] = 41;
    for (const auto& [name, alter] : person)
        std::cout << name << " = " << alter << '\n';
    if (auto it = person.find("Dora"); it == person.end())
        std::cout << "Dora not found\n";
}

std::map is sorted by key; find returns an iterator (end() means: not present). For faster access without sorting, use std::unordered_map.

C#C#

var person = new Dictionary<string, string> { ["name"] = "Ada" };
person["stadt"] = "London";
foreach (var (schluessel, wert) in person)
{
    Console.WriteLine($"{schluessel} = {wert}");
}
Console.WriteLine(person.GetValueOrDefault("email", "no email"));

GetValueOrDefault returns a fallback value instead of a KeyNotFoundException; foreach deconstructs each pair directly into key and value.

GoGo

package main

import "fmt"

func main() {
	person := map[string]string{"name": "Ada"}
	person["stadt"] = "London"
	for k, v := range person {
		fmt.Println(k, "=", v)
	}
	email, ok := person["email"]
	fmt.Printf("%q %v\n", email, ok)
}

The second return value (ok) tells you whether the key exists; missing keys yield the zero value (""). The order of range over maps is random.

RsRust

use std::collections::HashMap;

fn main() {
    let mut person: HashMap<&str, &str> = HashMap::new();
    person.insert("name", "Ada");
    person.insert("stadt", "London");
    for (schluessel, wert) in &person {
        println!("{schluessel} = {wert}");
    }
    println!("{}", person.get("email").unwrap_or(&"no email"));
}

get returns an Option<&V> instead of an error. The iteration order of a HashMap is not fixed (use BTreeMap for sorting).

PHPPHP

<?php
$person = ["name" => "Ada", "alter" => 36];
$person["stadt"] = "London";
foreach ($person as $schluessel => $wert) {
    echo "$schluessel = $wert\n";
}
echo $person["email"] ?? "no email", "\n";

In PHP the map is the same thing as the normal array. ?? returns a default value if the key is missing – without a warning.

RbRuby

person = { name: "Ada", alter: 36 }
person[:stadt] = "London"
person.each { |schluessel, wert| puts "#{schluessel} = #{wert}" }
puts person.fetch(:email, "no email")

Symbols (:name) are the usual keys. fetch returns a default value (or raises KeyError) instead of silently giving nil.

SwSwift

var person = ["name": "Ada", "alter": "36"]
person["stadt"] = "London"
for (schluessel, wert) in person.sorted(by: { $0.key < $1.key }) {
    print(schluessel, "=", wert)
}
print(person["email", default: "no email"])

Access returns an optional; default: provides a fallback. Dictionaries are unordered, so sort first for a fixed output.

KtKotlin

fun main() {
    val person = mutableMapOf<String, Any>("name" to "Ada", "alter" to 36)
    person["stadt"] = "London"
    for ((schluessel, wert) in person) {
        println("$schluessel = $wert")
    }
    println(person["email"] ?: "no email")
}

Accessing map[key] returns null for a missing key; the Elvis operator ?: provides a fallback value.

SQLSQL

SELECT kategorie,
       COUNT(*)              AS anzahl,
       ROUND(AVG(preis), 2)  AS schnitt,
       MAX(preis)            AS teuerstes
FROM produkte
GROUP BY kategorie
ORDER BY anzahl DESC, kategorie;

GROUP BY creates one value (aggregate) per key (category) – the SQL counterpart to a dictionary/map with a counter. Every column in the SELECT must be either grouped or aggregated.

shBash

declare -A person=([name]="Ada" [alter]=36)
person[stadt]="London"
for schluessel in "${!person[@]}"; do
  echo "$schluessel = ${person[$schluessel]}"
done
echo "E-Mail: ${person[email]:-no email}"

declare -A creates a dictionary (Bash 4+, not in the macOS system Bash 3.2). ${!person[@]} returns the keys; the order is not guaranteed.

</>HTML & CSS

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; }
dt { font-weight: 700; } dd { margin: 0; }
table { border-collapse: collapse; margin-top: 12px; }
th, td { border: 1px solid #bbb; padding: 4px 12px; text-align: left; }
th { background: #eee; }
</style>
<dl><dt>Name</dt><dd>Ada Lovelace</dd><dt>Profession</dt><dd>Mathematician</dd></dl>
<table>
  <tr><th>Country</th><th>Capital</th></tr>
  <tr><td>DE</td><td>Berlin</td></tr>
  <tr><td>FR</td><td>Paris</td></tr>
</table>

The counterpart of a map: <dl> with <dt> (key) and <dd> (value) for individual mappings, <table> for several records with the same columns (like a list of maps).

More comparisons

Hello World Variables Conditionals Loops Functions Lists and Arrays Classes and Objects Error Handling Reading Files