Python Dictionaries: Exercises

30 Python Dictionary Exercises for Mastery

Explore these exercises to solidify your understanding of Python dictionaries. Each exercise is designed to cover various aspects of dictionary usage. Check the answers at the bottom of the page.

Exercises

  1. Create a dictionary named contacts with the keys "name", "phone", and "email". Initialize it with your own contact details. (Exercise 1)
  2. Add a new key-value pair to the contacts dictionary where the key is "address" and the value is your home address. (Exercise 2)
  3. Update the "phone" number in the contacts dictionary to a new value. (Exercise 3)
  4. Remove the "email" key from the contacts dictionary. (Exercise 4)
  5. Write a function create_book that takes a list of book titles and returns a dictionary with the titles as keys and None as values. (Exercise 5)
  6. Write a function get_value that takes a dictionary and a key, and returns the value associated with that key. Handle the case where the key might not exist. (Exercise 6)
  7. Given a dictionary of fruits with their quantities, find and print the total quantity of all fruits. (Exercise 7)
  8. Create a dictionary person with nested dictionaries for "address" and "contacts". Print the city from the nested "address" dictionary. (Exercise 8)
  9. Use the fromkeys() method to create a dictionary with keys "a", "b", and "c", and all values set to 0. (Exercise 9)
  10. Write a program to merge two dictionaries into one. Print the resulting dictionary. (Exercise 10)
  11. Sort a dictionary by its keys and print the sorted dictionary. (Exercise 11)
  12. Use the setdefault() method to add a new key-value pair to a dictionary only if the key does not already exist. (Exercise 12)
  13. Write a function that takes a dictionary and a key, and returns the key-value pair if it exists; otherwise, return "Key not found". (Exercise 13)
  14. Count the number of unique values in a dictionary and print the result. (Exercise 14)
  15. Use the pop() method to remove a specific key-value pair from a dictionary. Print the removed item and the updated dictionary. (Exercise 15)
  16. Print all keys in the dictionary using the keys() method. (Exercise 16)
  17. Print all values in the dictionary using the values() method. (Exercise 17)
  18. Print all key-value pairs in the dictionary using the items() method. (Exercise 18)
  19. Write a dictionary comprehension to create a dictionary of squares for numbers 1 through 10. (Exercise 19)
  20. Use the copy() method to create a copy of a dictionary and modify the copy without affecting the original. (Exercise 20)
  21. Check if a specific key exists in the dictionary using the in operator and print a corresponding message. (Exercise 21)
  22. Calculate the average of numerical values in a dictionary where the keys are names and the values are grades. (Exercise 22)
  23. Find the day with the highest temperature from a dictionary where the keys are days and the values are temperatures. (Exercise 23)
  24. Remove items from a dictionary where the value is None. (Exercise 24)
  25. Print all key-value pairs in a formatted manner. (Exercise 25)
  26. Create a dictionary of cubes for numbers from 1 to 10 using dictionary comprehension. (Exercise 26)
  27. Merge multiple dictionaries into one, ensuring that values from the last dictionary overwrite earlier ones. (Exercise 27)
  28. Find the length of a dictionary (i.e., the number of key-value pairs). (Exercise 28)
  29. Count the occurrences of each character in a string and store the results in a dictionary. (Exercise 29)
  30. Swap the keys and values in a dictionary and print the new dictionary. (Exercise 30)

Answers

  1. Example dictionary:
    contacts = {"name": "John Doe", "phone": "555-1234", "email": "[email protected]"}
  2. Update with address:
    contacts["address"] = "123 Main St, Anytown, USA"
  3. Update phone number:
    contacts["phone"] = "555-5678"
  4. Remove email:
    del contacts["email"]
  5. Function to create book dictionary:
    def create_book(titles):
    return {title: None for title in titles}
  6. Function to get value:
    def get_value(dictionary, key):
    return dictionary.get(key, "Key not found")
  7. Total quantity of fruits:
    fruit_dict = {"apple": 10, "banana": 5, "orange": 7}
    total_quantity = sum(fruit_dict.values())
  8. Nested dictionary for person:
    person = {"address": {"city": "New York", "zip": "10001"}, "contacts": {"phone": "555-1234", "email": "[email protected]"}}
    print(person["address"]["city"])
  9. Create dictionary with fromkeys():
    keys = ["a", "b", "c"]
    new_dict = dict.fromkeys(keys, 0)
  10. Merge dictionaries:
    dict1 = {"a": 1, "b": 2}
    dict2 = {"c": 3, "d": 4}
    merged_dict = {**dict1, **dict2}
  11. Sort dictionary by keys:
    sorted_dict = dict(sorted(dictionary.items()))
  12. Add key-value pair with setdefault():
    dictionary.setdefault("new_key", "default_value")
  13. Function to return key-value pair:
    def find_pair(dictionary, key):
    return dictionary.get(key, "Key not found")
  14. Count unique values:
    unique_values = len(set(dictionary.values()))
  15. Remove key-value pair with pop():
    removed_item = dictionary.pop("key_to_remove")
    print("Removed:", removed_item)
    print("Updated Dictionary:", dictionary)
  16. Print all keys:
    for key in dictionary.keys():
    print(key)
  17. Print all values:
    for value in dictionary.values():
    print(value)
  18. Print all key-value pairs:
    for
    
     key, value in dictionary.items():
    print(f"{key}: {value}")
  19. Create dictionary of squares:
    squares = {x: x**2 for x in range(1, 11)}
  20. Create copy of dictionary:
    copied_dict = original_dict.copy()
  21. Check if key exists:
    if "key" in dictionary:
    print("Key exists")
  22. Calculate average of grades:
    grades = {"John": 85, "Alice": 90, "Bob": 78}
    average = sum(grades.values()) / len(grades)
  23. Find day with highest temperature:
    temperatures = {"Monday": 70, "Tuesday": 75, "Wednesday": 80}
    highest_day = max(temperatures, key=temperatures.get)
  24. Remove items with None values:
    cleaned_dict = {k: v for k, v in dictionary.items() if v is not None}
  25. Print all key-value pairs formatted:
    for key, value in dictionary.items():
    print(f"Key: {key}, Value: {value}")
  26. Create dictionary of cubes:
    cubes = {x: x**3 for x in range(1, 11)}
  27. Merge multiple dictionaries:
    dicts = [{"a": 1}, {"b": 2}, {"c": 3}]
    merged_dict = {}
    for d in dicts:
    merged_dict.update(d)
  28. Find dictionary length:
    length = len(dictionary)
  29. Count character occurrences:
    string = "hello world"
    char_count = {char: string.count(char) for char in set(string)}
  30. Swap keys and values:
    swapped_dict = {v: k for k, v in dictionary.items()}

Leave a Comment

Simple, privacy focused and free ad network for websites in need of new visitors. Free & easy backlink link building. Overseas domestic helper.