Atom

Dictionaries

A dictionary stores values under keys. Use it when a name such as health is more useful than a position such as item 2.

Create a dictionary

Use braces and give each field a name and a starting value.

Atom
player = {
    name = 'Ada'
    health = 100
}
print(count(player))
Output
2

The dictionary has two entries.

Read a field

Dot syntax is convenient when you know the field name while writing the program.

Atom
player = {name = 'Ada', health = 100}
print(player.name)
Output
Ada

The name field contains the text Ada.

Change an existing field

Subtract ten from the recorded health.

Atom
player = {health = 100}
player.health -= 10
print(player.health)
Output
90

The update changes the existing entry.

Add a new key

Use brackets when the key comes from a variable.

Atom
player = {name = 'Ada'}
field = 'score'
player[field] = 5
print(player.score)
Output
5

Assigning to the missing key creates it.

Remove a key

Pass the dictionary and the key to remove().

Atom
player = {name = 'Ada', bonus = 5}
print(remove(player, 'bonus'))
print(count(player))
Output
5
1

remove() returns the deleted value. The name field remains.

Visit keys and values

Give the loop two bindings to read a key and its value together.

Atom
player = {name = 'Ada', health = 90}
for key, value in player:
    print('{key}: {value}')
Output
name: Ada
health: 90

The dictionary visits the keys in insertion order.

Copy a dictionary

Make a separate top-level dictionary before changing the copy.

Atom
player = {health = 90}
saved = copy(player)
saved.health = 100
print(player.health)
Output
90

The original field is unchanged. A shallow copy still shares any nested objects.