Lists and dicts

A list is a string in a fixed format: words with spaces between them, and braces around a word that has a space. A dict is a list of keys and values. This lesson makes the notes of jot a list of dicts.

Lists

list makes a list and adds the braces that each word needs: set tags [list home "the shop" work]. llength $tags counts the elements, and lindex $tags 1 gets one. The first index is 0, and end is the last one: lindex $tags end.

lappend adds to a list in a variable: lappend tags garden. lsort $tags sorts it, lsearch $tags work finds an element, and join $tags ", " makes one string.

Tcl Python
list a b c ["a", "b", "c"]
lindex $l 0 l[0]
lrange $l 1 end l[1:]
lappend l d l.append("d")
foreach x $l { ... } for x in l:

A list made with quotes

A string in quotes is a list only when its words are right. set name "the shop" has a space. llength "home $name" gives 3: the quotes made the text home the shop, and the shop is now two elements. llength [list home $name] keeps the shop as one element. Build a list with list and lappend, and never with quotes.

Dicts

set n [dict create text "buy milk" done 0] makes a dict for a note. dict get $n text gets a value, and dict set n done 1 changes the variable. A missing key is an error: dict get $n tags. Check with dict exists $n tags first.

Now the notes of jot are a list of dicts. set notes [list $n [dict create text "fix the bike" done 0]] makes it, and dict get [lindex $notes 1] text reads the second note. lmap x $notes {dict get $x text} gets the text of each note.

Reading code an agent wrote

Ask an agent

Store each note as a Tcl dict with the keys text, done, and tags. Use dict exists before each dict get of an optional key.

Try this

The state of the shell at the start of this lesson
set note "buy milk"
set count 1