Exercise: Dictionaries

Exercise 1: Create a Word Count Dictionary

Task: Write a function that counts the frequency of each word in a given list.

Instructions:

  • Define a function called word_count(word_list) that takes a list of strings word_list.
  • Inside the function, create a dictionary to store the word counts.
  • Loop through the list and update the dictionary with the frequency of each word.
  • Return the dictionary.
  • Call the function with a sample list (e.g., ["NLP", "is", "fun", "NLP"]) and print the result.
Show solution
def word_count(word_list):
    count_dict = {}
    
    for word in word_list:
        count_dict[word] = count_dict.get(word, 0) + 1
    
    return count_dict

# Sample usage
words = ["NLP", "is", "fun", "NLP"]
result = word_count(words)
print("Word count dictionary:", result)  
Word count dictionary: {'NLP': 2, 'is': 1, 'fun': 1}

Exercise: Manage a Simple Chat Log

Task: Create a simple chat log data structure using a dictionary to store messages between a user and a chatbot.

Instructions:

  1. Define a function called create_chat_log() that initializes an empty chat log dictionary.
  2. Define another function called add_message(chat_log, sender, message) that takes the chat log, a sender (“user” or “chatbot”), and the message as parameters.
    • The function should append the new message to a list under the appropriate sender in the chat log.
  3. Define a function called get_chat_log(chat_log) that returns the entire chat log.
  4. Call the functions to create a chat log, add messages from both the user and the chatbot, and then print the entire chat log.

Example structure of the chat log:

{
    "user": ["Hello!", "What is NLP?"],
    "chatbot": ["Hi there!", "NLP stands for Natural Language Processing."]
}

<details>
<summary>Show solution</summary>

::: {#cell-7 .cell execution_count=2}
``` {.python .cell-code}
def create_chat_log():
    return {"user": [], "chatbot": []}

def add_message(chat_log, sender, message):
    if sender in chat_log:
        chat_log[sender].append(message)
    else:
        print("Sender not recognized. Use 'user' or 'chatbot'.")

def get_chat_log(chat_log):
    return chat_log

# Example usage
chat_log = create_chat_log()
add_message(chat_log, "user", "Hello!")
add_message(chat_log, "chatbot", "Hi there!")
add_message(chat_log, "user", "What is NLP?")
add_message(chat_log, "chatbot", "NLP stands for Natural Language Processing.")

# Print the chat log
print("Chat Log:", get_chat_log(chat_log))
Chat Log: {'user': ['Hello!', 'What is NLP?'], 'chatbot': ['Hi there!', 'NLP stands for Natural Language Processing.']}

:::

Back to top