Introduction
Introduction to dictionaries
Dictionaries are a fundamental data structure in programming that allow you to store and retrieve data in a structured and organized manner. They are also known as associative arrays, hash maps, or hash tables in some programming languages.
In simple terms, a dictionary is like a real-life dictionary or a phone book. It consists of a collection of key-value pairs, where each key is unique and associated with a corresponding value. Think of the keys as the words in a dictionary, and the values as their respective definitions.
Dictionaries provide efficient and fast look-up operations by using a technique called hashing. This means that instead of searching through the entire collection of data, the dictionary uses a unique hash code generated from the key to quickly locate the associated value.
One of the key benefits of dictionaries is their versatility in storing different types of data. The keys can be of any immutable type, such as strings, numbers, or tuples, while the values can be of any data type, including numbers, strings, lists, or even other dictionaries.
Example 1
Example 1 – Name and address adder
This simple program asks the user to enter names and ages and them adds them to a dictionary.
name_age_dict = {} while True: name = input("Enter a name (or 'q' to quit): ") if name == 'q': break age = input("Enter the age for {}: ".format(name)) age = int(age) # Convert age to an integer name_age_dict[name] = age print("Names and ages:") for name, age in name_age_dict.items(): print("{}: {} years old".format(name, age))
Example 2
Example 2 – Letter counter
In this example we write a simple function that keeps track of the numbers of times letters are contained within a string.
def count_letter_occurrences(string): letter_count = {} for letter in string: if letter.isalpha(): letter = letter.lower() # Convert letter to lowercase for case-insensitive counting if letter in letter_count: letter_count[letter] += 1 else: letter_count[letter] = 1 return letter_count # Example usage sentence = "Hello, world!" occurrences = count_letter_occurrences(sentence) for letter, count in occurrences.items(): print(f"Letter '{letter}' occurs {count} times.")
Uses of dictionaries
Dictionaries programming challenges
- Word Counter: Write a program that counts the occurrences of words in a given sentence or text. Use a dictionary to store the words as keys and their corresponding counts as values. Iterate through the text, update the counts in the dictionary, and display the results.
- Contact Book: Create a program that allows users to store and retrieve contact information. Use a dictionary to represent each contact, where the keys are names and the values are phone numbers or email addresses. Implement features like adding new contacts, searching for a contact by name, and displaying the entire contact book.
- Weather App: Build a program that retrieves weather data for different cities. Use a dictionary to map city names to their corresponding weather information, such as temperature, humidity, or weather conditions. Allow users to enter a city name, look up the weather data in the dictionary, and display it.
- Quiz Game: Develop a program that presents a quiz to the user. Store the quiz questions as keys in a dictionary, with the corresponding answers as the values. Randomly select questions from the dictionary and prompt the user for answers. Keep track of their score by comparing their answers with the values in the dictionary.
- Student Grade Calculator: Design a program that calculates and displays students’ grades based on their scores. Use a dictionary to map students’ names to their scores. Allow the user to enter the scores for each student, calculate their grades using predefined criteria, and display the final results with the corresponding grades.