Tcl dictionaries
last modified November 24, 2026 Tcl 8.6
A Tcl dictionary maps keys to values. It is still a string, written as an even
list of keys and values, so it can be stored in a variable, passed to a
procedure or written to a file without conversion. Tcl 8.6 provides a complete
set of dict subcommands that read and update that string
efficiently.
This article starts with create, get and set, then covers existence tests, iteration, merging, counters and nested records. Most subcommands take a dictionary value, but a few take the name of a variable because they modify it; that difference is the main source of confusion. The dict command page is the full reference.
Creating and reading dictionaries
dict create builds a dictionary from alternating keys and values,
dict get reads one value, and dict size counts pairs.
Keys are ordinary strings, values can be any string, and a value containing
spaces is braced in the string form.
set user [dict create name Jane age 28 city Bratislava] puts "record: $user" puts "name: [dict get $user name]" puts "age: [dict get $user age]" puts "pairs: [dict size $user]"
The record prints as one line, which is exactly what the variable holds.
dict get returns the value for one key and raises an error when the
key is absent, so it is normally paired with an existence test. The
set page covers the plain variable commands that
dictionaries complement.
$ tclsh create.tcl record: name Jane age 28 city Bratislava name: Jane age: 28 pairs: 3
Setting and removing keys
dict set adds a key or replaces its value. Like
dict unset, it takes the name of a variable as its first argument
and updates that variable, returning the new dictionary.
dict remove takes a value instead and returns a modified copy,
leaving the original alone.
set cfg [dict create host localhost port 8080 debug 0] dict set cfg port 9090 dict set cfg user admin puts "after set: $cfg" puts "has user: [dict exists $cfg user]" puts "has password: [dict exists $cfg password]" set cfg [dict unset cfg debug] puts "after unset: $cfg" puts "has debug: [dict exists $cfg debug]" puts "still port: [dict get $cfg port]"
Setting port replaces an existing value while keeping its position,
and setting user appends a new pair. dict exists
reports presence without an error, which is how the script checks for
password before reading it. dict unset removes
debug from the variable, and the last line confirms that the other
keys are untouched. Assigning the result back is a safe habit even though
dict unset already modified the variable.
$ tclsh set_unset.tcl after set: host localhost port 9090 debug 0 user admin has user: 1 has password: 0 after unset: host localhost port 9090 user admin has debug: 0 still port: 9090
Keys, values and size
dict keys and dict values return lists in insertion
order, and dict size counts pairs. dict keys accepts a
glob pattern, and dict filter selects whole pairs by key or by
value, returning a dictionary.
set request [dict create host example.com port 443 path /api timeout 30] puts "size: [dict size $request]" puts "keys: [dict keys $request]" puts "values: [dict values $request]" puts "sorted: [lsort [dict keys $request]]" puts "glob: [dict keys $request *ti*]" puts "filter: [dict filter $request key *ti*]" puts "values matching 4*: [dict filter $request value 4*]"
The four keys appear in the order they were created, not alphabetically, which
is why the sorted line exists. The pattern *ti* keeps only
timeout, while the value pattern 4* keeps the pair
whose port starts with a four. dict filter returns a dictionary, so
its result can be passed straight to another dict command. The
lsort page covers sorting when a fixed order is
needed.
$ tclsh keys.tcl size: 4 keys: host port path timeout values: example.com 443 /api 30 sorted: host path port timeout glob: timeout filter: timeout 30 values matching 4*: port 443
Walking a dictionary
dict for iterates over key and value variables and is the normal way
to process every pair. dict with goes further: it copies the values
into local variables for the duration of a script and writes them back when the
script ends, so a record can be read and updated without repeating the key
names.
set scores [dict create Alice 91 Bob 78 Carol 85]
dict for {name score} $scores {
puts [format "%-6s %3d" $name $score]
}
set product [dict create name Keyboard price 49 quantity 3]
dict with product {
puts "$name total: [expr {$price * $quantity}]"
set price [expr {$price + 5}]
}
puts "product: $product"
The first loop prints a small score table. In the second block,
name, price and quantity behave like local
variables, and the new price is stored back in
product automatically. Unsetting one of the variables inside the
block would remove the key, so dict with is a compact way to edit a
fixed set of fields. The foreach page explains the
loop form that dict for follows.
$ tclsh for_with.tcl Alice 91 Bob 78 Carol 85 Keyboard total: 147 product: name Keyboard price 54 quantity 3
Merging and updating
dict merge combines dictionaries; when a key appears more than once
the rightmost value wins. dict update mirrors selected keys into
local variables, runs a script and writes the variables back, which is the
targeted version of dict with.
set defaults [dict create host localhost port 80 debug 0]
set overrides [dict create port 8080 debug 1]
set cfg [dict merge $defaults $overrides]
puts "merged: $cfg"
puts "port: [dict get $cfg port]"
puts "host: [dict get $cfg host]"
set state [dict create count 2 total 10 server {name app port 80}]
dict update state count c total t server s {
incr c
incr t $c
dict set s port 8081
}
puts "state: $state"
puts "replace: [dict replace $state count 99 new 1]"
The merged configuration takes port and debug from the
overrides and keeps host from the defaults. In the update block,
c and t are ordinary variables, and
dict set s port 8081 changes a nested dictionary that is written
back as well. dict replace is a simpler alternative when the keys
are known in advance.
$ tclsh merge.tcl
merged: host localhost port 8080 debug 1
port: 8080
host: localhost
state: count 3 total 13 server {name app port 8081}
replace: count 99 total 13 server {name app port 8081} new 1
Counters and list values
Two subcommands make a dictionary behave like a small database.
dict incr adds to a numeric value, treating a missing key as zero,
and dict lappend appends to a list value. Both take a variable name
and update it in place.
set stats [dict create]
dict incr stats visits
dict incr stats visits 4
dict lappend stats tags quick
dict lappend stats tags {needs review}
puts "stats: $stats"
puts "visits: [dict get $stats visits]"
puts "tags: [dict get $stats tags]"
set text "red green blue red red green"
set counts [dict create]
foreach word [split $text] {
dict incr counts $word
}
dict for {word n} $counts {
puts [format "%-6s %d" $word $n]
}
puts "distinct: [dict size $counts]"
The first block creates visits on the first call, adds four on the
second, and builds a list of tags with dict lappend. The second
block is the classic word count: one dict incr per word, then a loop
over the result. Insertion order means the words appear in the order they were
first seen, and dict size gives the number of distinct words.
$ tclsh counters.tcl
stats: visits 5 tags {quick {needs review}}
visits: 5
tags: quick {needs review}
red 3
green 2
blue 1
distinct: 3
Nested dictionaries
A dictionary value can be another dictionary. dict get accepts a
path of keys, and dict set creates missing intermediate
dictionaries, so a configuration tree needs no setup code.
set config [dict create \
server [dict create host localhost port 8080] \
database [dict create name app user admin]]
puts "host: [dict get $config server host]"
puts "db name: [dict get $config database name]"
dict set config server port 9090
dict set config database password secret
puts "server: [dict get $config server]"
dict set config cache ttl 60
puts "cache: [dict get $config cache ttl]"
puts "nested exists: [dict exists $config server port]"
puts "missing: [dict exists $config server tls]"
puts "as a string: $config"
dict get $config server host walks two levels, and
dict exists accepts the same path. Setting a key inside
server updates only that value, while setting
cache ttl creates the cache dictionary because it did
not exist. The printed form shows the nesting as braces, which is still one
valid Tcl list. Deeply nested data often reads better as an
array of records, but a nested dictionary is easier to
pass around and copy.
$ tclsh nested.tcl
host: localhost
db name: app
server: host localhost port 9090
cache: 60
nested exists: 1
missing: 0
as a string: server {host localhost port 9090} database {name app user admin password secret} cache {ttl 60}
Copies and key order
Dictionaries are values, not references. Assigning one to another variable
copies it, and a later dict set on the copy leaves the original
unchanged. Key order follows insertion: updating a key keeps its place, and a new
key is appended.
set a [dict create x 1 y 2]
set b $a
dict set b x 99
dict set b z 3
puts "a: $a"
puts "b: $b"
set d [dict create]
foreach key {zebra apple mango} {
dict set d $key 0
}
puts "insertion order: [dict keys $d]"
dict set d apple 1
puts "after update: [dict keys $d]"
puts "sorted: [lsort [dict keys $d]]"
set p {a 1 b 2}
set q {b 2 a 1}
puts "p keys: [dict keys $p]"
puts "q keys: [dict keys $q]"
puts "string equal: [string equal $p $q]"
puts "same size: [expr {[dict size $p] == [dict size $q]}]"
The copy has its own x, so a keeps the old value.
Updating apple does not move it, and a new key would go to the end;
lsort is the way to get a predictable listing. Two dictionaries can
hold the same pairs in a different order; their string forms differ, even though
every lookup returns the same value. Sorting keys before printing avoids output
that changes with insertion order.
$ tclsh copy.tcl a: x 1 y 2 b: x 99 y 2 z 3 insertion order: zebra apple mango after update: zebra apple mango sorted: apple mango zebra p keys: a b q keys: b a string equal: 0 same size: 1
Source
The dict page of the Tcl 8.6 manual documents every subcommand,
including the options of dict for, dict with,
dict update and dict filter. The
foreach and lsort pages cover the list commands used
alongside them.
This article covered Tcl dictionaries from creation to nested records: reading and writing keys, iterating, merging, counting and copying. Continue with Tcl scope and namespaces to see how a growing program keeps its procedures and variables apart.
Author
List all Tcl Tutorials.