SECTION 02 / 31

Create the dictionary before assigning entries

1 min read

Start with d = {}. This declares an empty dictionary. Then d[7] = 76 creates a key 7 and stores 76. d[21] = 74 creates a second entry. Square brackets after the dictionary name contain a KEY. Curly braces display the dictionary itself.

Initialize d as {}, then add the two actual course Chemistry entries.
Initialize d as {}, then add the two actual course Chemistry entries.
A separate illustrative update: assigning d[7] = 80 replaces its earlier 76. This does not change the original course record.
A separate illustrative update: assigning d[7] = 80 replaces its earlier 76. This does not change the original course record.
REAL COURSE DATA · KEYS, COUNTS AND CONNECTIONS

Create, replace and accumulate

Follow the dictionary as its keys and values change. Predict each lookup or update before revealing the next step.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next key, whether it already exists, and the value that will be stored.

d = {}
d[7] = 76
d[21] = 74
answer = d[21]     # 74

# Separate illustrative update, not a correction to the dataset:
d[7] = 80         # replace the previous value for key 7

Assignment has two cases: a missing key creates an entry; a present key gets a replacement value. It does not keep two entries with the same key. To keep multiple values, deliberately store a list or another dictionary as the one value.

Try it yourself

After d={} then d[7]=76 then d[7]=80, how many entries exist?

Show explained answer

One entry: {7:80}.

Try it yourself

What is wrong with trying d[7]=76 before creating d?

Show explained answer

The variable has not been initialized as a dictionary. Initialize d={} first.

Try it yourself

Does d[7]=80 add 80 to 76?

Show explained answer

No. Assignment replaces 76 with 80. Addition would require d[7]=d[7]+80.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑