Concepts / Dictionary Creation and Access

Dictionary Creation and Access

Dictionaries are ideal for counting and categorizing data because they map keys to values instantly.

  • Programming

From Raw Records to Counts

A dataset often contains repeated items, but the useful result is a summary of how often each item appears. A mail log, for example, can be summarized by counting messages for each day, sender, or email domain. A dictionary is well suited to this task because it maps each key to a value. The key identifies the category being counted, and the value stores the running count.

Key point

The central counting pattern is simple: check whether a key exists, initialize it to 0 if it does not, and then increment its value.

Sat3 messages3count for SatFri2 messages2count for Frimaps tomaps to
How are item keys connected to their occurrence counts, and what changes when an item appears again?

The Counting Pattern

Suppose each record produces one category key. For every record, first determine the key. If the dictionary has not seen that key before, give it an initial value of 0. Then increase the value by 1. When the same key appears again, the dictionary does not create a second entry. It updates the existing value instead.

Code walkthrough
counts = {}

for item in ["Sat", "Fri", "Sat"]:
    if item not in counts:
        counts[item] = 0
    counts[item] = counts[item] + 1

print(counts)
  1. 1
    The empty dictionary has no keys before the loop begins.
  2. 2
    For each item, the membership check determines whether initialization is needed.
  3. 3
    The increment statement runs for both new and existing keys.
  4. 4
    The final dictionary contains one key for each distinct item and its occurrence count.
  • counts starts as an empty dictionary.
  • The first Sat key is initialized and then increased to 1.
  • Fri is initialized and increased to 1.
  • The second Sat occurrence finds an existing key and increases its value to 2.
Output
{'Sat': 2, 'Fri': 1}
Before
counts = {}
item = "Sat"
if item not in counts:
    counts[item] = 0
counts[item] = counts[item] + 1

The dictionary has no Sat entry before the first occurrence.

After
counts = {"Sat": 1}
item = "Sat"
if item not in counts:
    counts[item] = 0
counts[item] = counts[item] + 1

The first occurrence creates the Sat key and stores a count of 1.

counts{}Satnew keycounts{'Sat': 1}Satcount 1does not containinitialize then incrementstores
What happens when code looks up an existing key versus encountering a key that is not yet in the dictionary?

Selecting the Useful Field

A mail log line contains several fields. The line starts with From, followed by an email address, then a day name such as Sat or Fri, followed by other information. The counting task determines which field becomes the dictionary key. To count messages by day, extract the day field. To count messages by sender, extract the full email address instead.

python
Output
Sat
Fromrecord markeralice@example.comemail addressSatdictionary keydetailsother informationselect fields[2]
Which part of each structured email record is extracted and used as the dictionary key?

From Addresses to Domains

A sender histogram uses the full email address as its key. A domain histogram groups senders more broadly. To create it, first extract the email address from the From line, then split the address at the @ symbol and use the part after @ as the dictionary key. Addresses from the same domain therefore contribute to the same count.

Code walkthrough
lines = [
    "From alice@umich.edu Sat details",
    "From bob@iupui.edu Fri details",
    "From carol@umich.edu Fri details"
]

domain_counts = {}

for line in lines:
    fields = line.split()
    email = fields[1]
    domain = email.split("@")[1]

    if domain not in domain_counts:
        domain_counts[domain] = 0
    domain_counts[domain] = domain_counts[domain] + 1

print(domain_counts)
  1. 1
    The loop processes one mail-log line at a time.
  2. 2
    Each line is split into fields so the email address can be selected.
  3. 3
    The email address is split at @, and the portion after it becomes the key.
  4. 4
    The counting pattern initializes unseen domains and increments every domain.
  • fields[1] selects the email address from each structured line.
  • email.split("@")[1] selects the domain portion after the @ symbol.
  • The first umich.edu message creates that domain key with a count of 1.
  • The second umich.edu message updates the existing key to 2.
Output
{'umich.edu': 2, 'iupui.edu': 1}
alice@umich.eduraw emailumich.edupart after @1initial countcarol@umich.eduraw email2updated countsplit at @initializesame extracted keyincrement
How does each raw email address become a domain key and update the corresponding count?

Tracking the Largest Count

After building a histogram, you can ask which key has the highest count. The maximum-loop pattern keeps two pieces of information: the key currently associated with the largest value and that largest value itself. As the loop examines each dictionary entry, it compares the entry's value with the current maximum. When the new value is larger, both tracked pieces of information are updated.

Code walkthrough
domain_counts = {
    "umich.edu": 2,
    "iupui.edu": 1,
    "example.edu": 4
}

max_key = None
max_value = None

for key in domain_counts:
    value = domain_counts[key]
    if max_value is None or value > max_value:
        max_key = key
        max_value = value

print(max_key)
print(max_value)
  1. 1
    The loop visits each key in the dictionary.
  2. 2
    The value for the current key is retrieved.
  3. 3
    The comparison checks whether no maximum exists yet or the current value is larger.
  4. 4
    When the comparison succeeds, max_key receives the current key and max_value receives its value.
  • max_key and max_value begin without a selected dictionary entry.
  • The first examined entry establishes the initial maximum.
  • A later entry replaces the maximum only when its value is larger.
  • The key and value are updated together so they remain associated.
Output
example.edu
4
No maximummax_key and max_value unsetumich.eduvalue 2umich.edumaximum 2iupui.eduvalue 1example.edumaximum 4example.eduvalue 4examineset maximumcompare 1 with 2continuereplace maximum
As the loop examines each dictionary entry, how does it track and update the key with the highest count?

Mistakes in Dictionary Counting

  • Common mistake

    Incrementing a key before initializing it

    What it looks like
    counts[item] = counts[item] + 1
    Why it fails

    A newly encountered item has no stored count yet.

    Do this instead

    Check whether the key exists, initialize it to 0 when necessary, and then increment it.

  • Common mistake

    Using the wrong field from a structured line

    What it looks like

    Using the email address when the task is to count by day

    Why it fails

    The dictionary then groups records by a different category from the one intended.

    Do this instead

    Split the line and select the field that represents the desired category.

  • Common mistake

    Counting full addresses when the task is to count domains

    What it looks like

    Using alice@umich.edu and carol@umich.edu as separate keys

    Why it fails

    The two messages come from the same domain but remain separated by their individual addresses.

    Do this instead

    Extract the portion after the @ symbol and use that domain as the key.

  • Common mistake

    Updating only the maximum value

    What it looks like
    max_value = value without also changing max_key
    Why it fails

    The stored maximum would no longer identify which dictionary key produced it.

    Do this instead

    Update max_key and max_value together whenever a larger count is found.

Practice the Transformation

MEDIUM

Given these structured records, describe the dictionary produced when counting by domain: From ana@umich.edu Sat details, From ben@iupui.edu Fri details, From cy@umich.edu Fri details. Then identify which domain has the larger count.

Hints
  • Select the email address after splitting each line.
  • Split the email address at @ and use the portion after it as the key.
  • Apply the initialization-and-increment pattern for each domain.
Worked example

Domain Count and Maximum

Count the domains in three mail-log records and find the domain with the highest count.

  1. 1
    Extract

    The email addresses are ana@umich.edu, ben@iupui.edu, and cy@umich.edu.

  2. 2
    Transform

    The domains are umich.edu, iupui.edu, and umich.edu.

  3. 3
    Count

    The resulting dictionary is {'umich.edu': 2, 'iupui.edu': 1}.

  4. 4
    Compare

    A maximum loop compares the values 2 and 1 and retains umich.edu as the key with the larger value.

Result

The domain with the highest count is umich.edu, with 2 messages.

Working Pattern

  • Identify the category you need before choosing a dictionary key.
  • Use split() to separate structured text into fields.
  • Use the correct field index for the record format.
  • Initialize unseen keys to 0 before incrementing their counts.
  • Use the full email address for sender counts and the portion after @ for domain counts.
  • When searching for the largest count, update the maximum key and maximum value together.

Key Takeaways

  1. 1
    A dictionary represents categories as keys and their occurrence counts as values.
  2. 2
    Counting requires checking for a key, initializing unseen keys to 0, and incrementing the value.
  3. 3
    Structured mail-log lines can provide different keys depending on the selected field: day, full email address, or domain.
  4. 4
    A domain count is created by extracting the part of an email address after the @ symbol.
  5. 5
    A maximum loop compares dictionary values and updates both the key and value when a larger count appears.

At a glance

  • Dictionaries map counting categories to occurrence totals.
  • The standard counting pattern initializes unseen keys and increments every key.
  • The selected field determines whether records are grouped by day, sender, or domain.
  • A maximum loop remembers the key and value associated with the largest count.
  • Email-domain aggregation transforms individual addresses into broader category counts.

Related concepts

More concepts starting with D