Dictionary

You can think of Dictionaries as a collection of data that is unorganized, unlike lists. Items in dictionaries are stored and fetched by a key, instead of a positional offset. Dictionaries can grow and shrink and can contain any objects at any nested level. They can also be changed in place. However, dictionaries do not support the sequence operations that work on strings and lists, such as slicing and concatenation, etc. They map keys to values. Dictionaries are written as {key:value} pairs, separated by commas.

Here we create a dictionary. The 'fruit' and 'Vegie' are the keys and the 'apple' and 'celery' are the values. We use the square bracket to index dictionaries by key as we did to index lists by offsets. The left to right positional order does not matter as it will change due to its unordered collection. The first key:value pair, for example, may not always be the same.

Here is an example of other ways to create dictionaries. All 4 make the same dictionary. The first is good if you can spell out the whole dictionary ahead of time. The second is good if you need to make one field at a time on teh fly. The third however requires all keys to be strings. The fourth is good if you need to build up keys and values as sequences at runtime.

In place change

This is the form of adding a new dictionary entry.

This example shows adding a new entry, however it is a nested dictionary. The last statement shows how to get a nested dictionary value. It is the same as lists, except using keys.