Dictionary Programs
Frequency of User Logins
users = ['john', 'bob', 'alex', 'alice', 'charlie', 'john',
'alex', 'alice', 'john', 'alex']
logins = {}
for username in users:
if username in logins:
logins[username] += 1
else:
logins[username] = 1
for user, count in logins.items():
print(f"{user:8} : {count} logins")
Word Frequency Counter
python
sentence = "apple banana orange apple apple banana grape orange apple"
words = sentence.split() # Split into a list of words
word_count = {} # Dictionary to store word counts
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Word Frequency:")
for word, count in word_count.items():
print(f"{word:8} : {count} times")
Output:
text
Word Frequency: apple : 4 times banana : 2 times orange : 2 times grape : 1 times
Key Similarities to Your Original Program:
- Uses a list of items (words instead of usernames).
- Counts occurrences using a dictionary.
- Prints formatted output.
Example 1: Voting System (Count Votes for Candidates)
python
votes = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Alice", "Alice", "Bob"]
vote_count = {}
for candidate in votes:
if candidate in vote_count:
vote_count[candidate] += 1
else:
vote_count[candidate] = 1
print("Election Results:")
for candidate, votes in vote_count.items():
print(f"{candidate:8} : {votes} votes")
Output:
text
Election Results: Alice : 4 votes Bob : 3 votes Charlie : 1 votes
Example 2: Product Inventory (Count Items Sold)
python
sales = ["Laptop", "Mouse", "Keyboard", "Laptop", "Mouse", "Monitor", "Laptop"]
inventory = {}
for product in sales:
if product in inventory:
inventory[product] += 1
else:
inventory[product] = 1
print("Products Sold:")
for product, quantity in inventory.items():
print(f"{product:8} : {quantity} units")
Output:
text
Products Sold: Laptop : 3 units Mouse : 2 units Keyboard : 1 units Monitor : 1 units