Dictionary Creation and Access
Dictionaries are ideal for counting and categorizing data because they map keys to values instantly.
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.
The central counting pattern is simple: check whether a key exists, initialize it to 0 if it does not, and then increment its value.
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.
counts = {}
for item in ["Sat", "Fri", "Sat"]:
if item not in counts:
counts[item] = 0
counts[item] = counts[item] + 1
print(counts)- 1The empty dictionary has no keys before the loop begins.
- 2For each item, the membership check determines whether initialization is needed.
- 3The increment statement runs for both new and existing keys.
- 4The 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.
{'Sat': 2, 'Fri': 1}counts = {}
item = "Sat"
if item not in counts:
counts[item] = 0
counts[item] = counts[item] + 1The dictionary has no Sat entry before the first occurrence.
counts = {"Sat": 1}
item = "Sat"
if item not in counts:
counts[item] = 0
counts[item] = counts[item] + 1The first occurrence creates the Sat key and stores a count of 1.
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.
SatFrom 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.
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)- 1The loop processes one mail-log line at a time.
- 2Each line is split into fields so the email address can be selected.
- 3The email address is split at @, and the portion after it becomes the key.
- 4The 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.
{'umich.edu': 2, 'iupui.edu': 1}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.
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)- 1The loop visits each key in the dictionary.
- 2The value for the current key is retrieved.
- 3The comparison checks whether no maximum exists yet or the current value is larger.
- 4When the comparison succeeds,
max_keyreceives the current key andmax_valuereceives its value.
max_keyandmax_valuebegin 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.
example.edu
4Mistakes in Dictionary Counting
Common mistake Incrementing a key before initializing it
What it looks likecounts[item] = counts[item] + 1Why it failsA newly encountered item has no stored count yet.
Do this insteadCheck 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 likeUsing the email address when the task is to count by day
Why it failsThe dictionary then groups records by a different category from the one intended.
Do this insteadSplit 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 likeUsing alice@umich.edu and carol@umich.edu as separate keys
Why it failsThe two messages come from the same domain but remain separated by their individual addresses.
Do this insteadExtract the portion after the @ symbol and use that domain as the key.
Common mistake Updating only the maximum value
What it looks likemax_value = value without also changing max_keyWhy it failsThe stored maximum would no longer identify which dictionary key produced it.
Do this insteadUpdate max_key and max_value together whenever a larger count is found.
Practice the Transformation
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.
Domain Count and Maximum
Count the domains in three mail-log records and find the domain with the highest count.
- 1Extract
The email addresses are ana@umich.edu, ben@iupui.edu, and cy@umich.edu.
- 2Transform
The domains are umich.edu, iupui.edu, and umich.edu.
- 3Count
The resulting dictionary is {'umich.edu': 2, 'iupui.edu': 1}.
- 4Compare
A maximum loop compares the values 2 and 1 and retains umich.edu as the key with the larger value.
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
- 1A dictionary represents categories as keys and their occurrence counts as values.
- 2Counting requires checking for a key, initializing unseen keys to 0, and incrementing the value.
- 3Structured mail-log lines can provide different keys depending on the selected field: day, full email address, or domain.
- 4A domain count is created by extracting the part of an email address after the @ symbol.
- 5A 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.