SECTION 14 / 31

A dictionary value can be another dictionary

1 min read
Create the outer birthday dictionary, create an empty inner dictionary for a new date, then add an ID → True entry.
Create the outer birthday dictionary, create an empty inner dictionary for a new date, then add an ID → True entry.
birthdays = {}
duplicates = {}
foreach X in scores {
    dob = normalizedDayMonth(X.DateOfBirth)
    id = X.CardNo
    if (isKey(birthdays,dob)) {
        duplicates[dob] = True
    }
    else {
        birthdays[dob] = {}
    }
    birthdays[dob][id] = True
}

birthdays[15 Mar] is now {7:True,21:True}. To find IDs, use keys(birthdays[15 Mar]). To ask whether ID 21 is in that date group, test isKey(birthdays[15 Mar],21). First check the outer date key before reading its inner dictionary.

The inner {} must be created only for a new date. Reinitializing it on every occurrence erases earlier IDs. With unique student records, the list and inner-dictionary versions identify the same students. If an ID is accidentally processed twice, a list retains the duplicate occurrence but an ID-keyed dictionary overwrites that ID’s True flag.

Try it yourself

What is the type of birthdays[15 Mar]?

Show explained answer

A dictionary whose keys are student IDs and values are True flags.

Try it yourself

What goes wrong if birthdays[dob]={} is executed for every record?

Show explained answer

It clears the existing group and loses earlier students at that date.

Try it yourself

Does an inner dictionary preserve repeated copies of the same ID?

Show explained answer

No. Each ID key has one current value. This differs from appending repeatedly to a list.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑