๐Ÿ“ฑ Code Python on your phone with Python Coding - Learn PythonGet the free Android app โ†’
  1. Home
  2. Python exercises
  3. Dictionary exercises

Python exercises ยท 6 tasks

Python dictionary exercises

Dictionaries map keys to values โ€” names to phone numbers, words to counts, IDs to records. These six exercises cover the patterns you'll use constantly.

Quick answerPractise Python dictionaries with six auto-checked exercises: a safe lookup with get(), counting letters, grouping words by first letter, inverting a dictionary, merging two score tables and reading nested data. The tests call your functions and compare the dictionaries they return.

0 / 6 solved

Dictionary essentials

d = {"a": 1} creates one; d["b"] = 2 adds a key; d.get("z", 0) reads a key with a fallback instead of raising KeyError; for key, value in d.items(): loops over pairs. Since Python 3.7 dictionaries keep insertion order, but the tests here compare dictionaries with ==, which ignores order.

Exercises

1. Price lookupeasy

Write price(item) that returns the price from the PRICES dictionary, or 0 if the item isn't on the menu.

    Show solution
    PRICES = {"coffee": 2.5, "tea": 2.0, "cake": 3.75}
    
    def price(item):
        return PRICES.get(item, 0)
    

    Square-bracket lookup raises KeyError for missing keys; get lets you choose a default.

    2. Letter frequencyeasy

    Write letter_counts(word) returning a dictionary of how many times each letter appears. "hello" โ†’ {'h': 1, 'e': 1, 'l': 2, 'o': 1}.

      Show solution
      def letter_counts(word):
          counts = {}
          for ch in word:
              counts[ch] = counts.get(ch, 0) + 1
          return counts
      

      Counting with a dictionary is one of the most common patterns in Python; collections.Counter(word) is the built-in shortcut.

      3. Group by first lettermedium

      Write group_words(words) that returns a dictionary mapping each first letter to the list of words starting with it, in the original order.

        Show solution
        def group_words(words):
            groups = {}
            for w in words:
                groups.setdefault(w[0], []).append(w)
            return groups
        

        setdefault returns the existing list, or inserts and returns a new empty one. collections.defaultdict(list) is the alternative.

        4. Invert a dictionarymedium

        Write invert(d) that swaps keys and values: {'a': 1, 'b': 2} โ†’ {1: 'a', 2: 'b'}.

          Show solution
          def invert(d):
              return {v: k for k, v in d.items()}
          

          If two keys share a value, the later one wins โ€” values must be unique (and hashable) for an inversion to be lossless.

          5. Merge score tablesmedium

          Write merge(a, b) that combines two dictionaries of scores, adding the values when a name appears in both. Don't modify a or b.

            Show solution
            def merge(a, b):
                out = dict(a)
                for name, score in b.items():
                    out[name] = out.get(name, 0) + score
                return out
            

            The starter's update overwrites Bob's 5 with 2 instead of adding โ€” and it changes a in place, a classic side-effect bug.

            6. Nested datahard

            students maps names to a dict with a list of scores. Write top_student(students) that returns the name with the highest average score.

              Show solution
              def top_student(students):
                  def average(name):
                      scores = students[name]["scores"]
                      return sum(scores) / len(scores)
                  return max(students, key=average)
              

              Looping over a dictionary gives its keys, so max(students, key=...) returns a name. A small helper function keeps the key readable.

              Next topic: Python basics โ†’

              Practise on your phone too

              Python Coding - Learn Python for Android: a real Python 3 interpreter, code editor, 26 example programs and 12 marked exercises.

              Get it on Google Play

              Frequently asked questions

              How do I avoid KeyError in a Python dictionary?

              Use d.get(key, default), check with if key in d, or use collections.defaultdict.

              Are Python dictionaries ordered?

              Yes, since Python 3.7 they keep insertion order. Comparing two dictionaries with == ignores order.

              Can a list be a dictionary key?

              No โ€” keys must be hashable (immutable). Use a tuple instead of a list.

              Keep practising

              Updated 2026-10-22 ยท every solution is tested on Python 3