a dictionary is an arrangement for mapping values to keys. the syntax for the conventional dictionary is shown below −
dict set dictname key value # or dict create dictname key1 value1 key2 value2 .. keyn valuen
some examples for creating a dictionary are shown below −
#!/usr/bin/tclsh dict set colours colour1 red puts $colours dict set colours colour2 green puts $colours set colours [dict create colour1 "black" colour2 "white"] puts $colours
when the above code is executed, it produces the following result −
colour1 red colour1 red colour2 green colour1 black colour2 white
size of dict
the syntax for getting size of dict is shown below −
[dict size dictname]
an example for printing the size is shown below −
#!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] puts [dict size $colours]
when the above code is executed, it produces the following result −
2
dictionary iteration
a simple dictionary iteration for printing keys and valued of the dictionary is shown below −
#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
foreach item [dict keys $colours] {
set value [dict get $colours $item]
puts $value
}
when the above code is executed, it produces the following result −
black white
value for key in dict
the syntax for retrieving value for key in dict is shown below −
[dict get $dictname $keyname]
an example for retrieving value for key is given below −
#!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] set value [dict get $colours colour1] puts $value
when the above code is executed, it produces the following result −
black
all keys in dict
the syntax for retrieving all keys in dict is shown below −
[dict keys $dictname]
an example for printing all keys is shown below −
#!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] set keys [dict keys $colours] puts $keys
when the above code is executed, it produces the following result −
colour1 colour2
all values in dict
the syntax for retrieving all values in dict is shown below −
[dict values $dictname]
an example for printing all values is shown below −
#!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] set values [dict values $colours] puts $values
when the above code is executed, it produces the following result −
black white
key exists in dict
the syntax for checking if a key exists in dict is shown below −
[dict exists $dictname $key]
an example for checking if a key exists in dict is shown below −
#!/usr/bin/tclsh set colours [dict create colour1 "black" colour2 "white"] set result [dict exists $colours colour1] puts $result
when the above code is executed, it produces the following result −
1