Skip to content
Laviyx Learn

Try

Python Dictionaries, Sets and Tuples Practice

Practise counting and grouping with dictionaries, comparing groups with sets, and packing and unpacking tuples.

Beginner9 problemsUpdated

Review first: Dictionaries, Sets, Tuples

  1. 1.Word frequency

    Beginner

    Count how many times each word appears in text = "red blue red green blue red", then print each word and its count in alphabetical order.

    Show hint

    counts[word] = counts.get(word, 0) + 1 adds one, starting from 0 for a new word.

    Show solution
    Python
    text = "red blue red green blue red"
    
    counts = {}
    for word in text.split():
        counts[word] = counts.get(word, 0) + 1
    
    for word in sorted(counts):
        print(word, counts[word])
    Output
    blue 2
    green 1
    red 3

    collections.Counter(text.split()) does the same counting in one line, and .most_common() sorts by count.

  2. 2.Safe lookups

    Beginner

    Given phone_book = {"Asha": "98200 11111", "Ravi": "98300 22222"}, print the numbers for Asha and Meera. For a name that is not in the book, print not found instead of crashing. Then add Meera's number 98400 33333 and print how many entries there are.

    Show hint

    phone_book["Meera"] raises a KeyError; phone_book.get("Meera", "not found") does not.

    Show solution
    Python
    phone_book = {"Asha": "98200 11111", "Ravi": "98300 22222"}
    
    for name in ["Asha", "Meera"]:
        print(name, phone_book.get(name, "not found"))
    
    phone_book["Meera"] = "98400 33333"
    print(len(phone_book), "entries")
    Output
    Asha 98200 11111
    Meera not found
    3 entries
  3. 3.Average marks per student

    Beginner

    Print each student's average mark, rounded to 1 decimal place:

    marks = {"Asha": [88, 92, 79], "Ravi": [75, 64, 81], "Meera": [95, 90, 98]}

    Show hint

    Loop with .items() to get each name and list together. The average is sum(list) / len(list).

    Show solution
    Python
    marks = {"Asha": [88, 92, 79], "Ravi": [75, 64, 81], "Meera": [95, 90, 98]}
    
    for name, scores in marks.items():
        average = sum(scores) / len(scores)
        print(f"{name}: {average:.1f}")
    Output
    Asha: 86.3
    Ravi: 73.3
    Meera: 94.3
  4. 4.Group words by first letter

    Beginner

    Group words = ["apple", "banana", "avocado", "cherry", "blueberry", "apricot"] into a dictionary where each key is a first letter and each value is the list of words starting with it. Print the dictionary.

    Show hint

    groups.setdefault(letter, []) returns the existing list for that letter, or creates an empty one.

    Show solution
    Python
    words = ["apple", "banana", "avocado", "cherry", "blueberry", "apricot"]
    
    groups = {}
    for word in words:
        groups.setdefault(word[0], []).append(word)
    
    print(groups)
    Output
    {'a': ['apple', 'avocado', 'apricot'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

    Dictionaries keep insertion order, so the keys appear in the order their first word was seen. collections.defaultdict(list) is another common way to write this.

  5. 5.Compare two clubs

    Beginner

    Given chess = {"Asha", "Ravi", "Meera", "John"} and music = {"Meera", "Priya", "John", "Kiran"}, print (as sorted lists):

    1. students in both clubs
    2. students in either club
    3. students only in chess
    Show hint

    & is intersection, | is union and - is difference. Wrap each result in sorted() because sets have no order.

    Show solution
    Python
    chess = {"Asha", "Ravi", "Meera", "John"}
    music = {"Meera", "Priya", "John", "Kiran"}
    
    print(sorted(chess & music))
    print(sorted(chess | music))
    print(sorted(chess - music))
    Output
    ['John', 'Meera']
    ['Asha', 'John', 'Kiran', 'Meera', 'Priya', 'Ravi']
    ['Asha', 'Ravi']

    Printing a set directly can show the names in a different order each time the program runs, so sort before printing whenever the order matters.

  6. 6.Remove duplicates, keep order

    Beginner

    Remove the duplicates from visits = ["home", "about", "home", "blog", "about", "contact"] while keeping the first-seen order.

    Show hint

    list(set(visits)) loses the order. dict.fromkeys(visits) keeps it, because dictionary keys are unique and ordered.

    Show solution
    Python
    visits = ["home", "about", "home", "blog", "about", "contact"]
    
    unique = list(dict.fromkeys(visits))
    
    print(unique)
    Output
    ['home', 'about', 'blog', 'contact']
  7. 7.Swap keys and values

    Beginner

    Turn codes = {"IN": "India", "JP": "Japan", "FR": "France"} into a dictionary that maps each country name to its code, and print the code for Japan.

    Show hint

    Loop over .items() and build a new dictionary with new[value] = key, or use a dictionary comprehension.

    Show solution
    Python
    codes = {"IN": "India", "JP": "Japan", "FR": "France"}
    
    by_country = {country: code for code, country in codes.items()}
    
    print(by_country)
    print(by_country["Japan"])
    Output
    {'India': 'IN', 'Japan': 'JP', 'France': 'FR'}
    JP

    This only works safely when the values are unique. If two keys shared a value, the later one would overwrite the earlier one in the new dictionary.

  8. 8.Unpack tuples

    Beginner

    Given points = [(2, 3), (-1, 5), (4, -2)], print each point as x=2, y=3. Then swap the variables a = 1 and b = 2 in a single line and print them.

    Show hint

    for x, y in points: unpacks each tuple. a, b = b, a swaps two variables.

    Show solution
    Python
    points = [(2, 3), (-1, 5), (4, -2)]
    
    for x, y in points:
        print(f"x={x}, y={y}")
    
    a = 1
    b = 2
    a, b = b, a
    print(a, b)
    Output
    x=2, y=3
    x=-1, y=5
    x=4, y=-2
    2 1
  9. 9.Tuples cannot change

    Beginner

    Create rgb = (255, 128, 0), try to change its first value to 0, and catch the error to print its message. Then create a new tuple with the first value changed and print it.

    Show hint

    Assigning to rgb[0] raises a TypeError. Build a new tuple with (0,) + rgb[1:].

    Show solution
    Python
    rgb = (255, 128, 0)
    
    try:
        rgb[0] = 0
    except TypeError as error:
        print("Error:", error)
    
    new_rgb = (0,) + rgb[1:]
    print(new_rgb)
    Output
    Error: 'tuple' object does not support item assignment
    (0, 128, 0)

    The comma makes a tuple, not the brackets, so (0,) is a one-item tuple, while (0) is just the number 0.