A learning repository for Python programming exercises. https://ekika.co/learn-python
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

3.3 KiB

📘 Python Dictionary Exercises

These exercises will allow you working with Python dict. You’ll learn nested structures, lookups, merges, transformations, filtering, and frequency maps — foundational for JSON, API, and data processing.


PYEKX-2ce5579c

Invert a Dictionary (Simple)

Problem

Write a function invert_dict(d) that swaps keys and values.

Example

invert_dict({'a': 1, 'b': 2})
# Output: {1: 'a', 2: 'b'}

Why? (Why it matters)

  • Useful in reverse lookups.
  • Found in config parsers, ENUM-like mappings, and translation systems.
  • Reversing data relationships is common in APIs and normalization.

Pro Constraints

  • Assume all values are unique and hashable.
  • Must not mutate the input dictionary.
  • Bonus: Extend to many-to-one values: {1: ['a', 'b']} if both a and b mapped to 1.

PYEKX-7b549e55

Merge Dictionaries with Conflict Resolution

Problem

Write merge_dicts(a, b) where b overrides values in a.

Add a mode argument:

  • 'override' (default): b overwrites a.
  • 'sum': if values are numeric, sum them.
  • 'append': create lists for conflicting keys.

Example

merge_dicts({'x': 2}, {'x': 3}, mode='sum')
# Output: {'x': 5}

Why?

  • Merging config files, environment overrides.
  • Inventory and accounting systems often need conflict handling logic.
  • Avoids accidental overwrites by making intent explicit.

Pro Constraints

  • Must not mutate original dicts.
  • Use pure dict operations only (no collections.ChainMap, etc.).
  • Bonus: Support deeply nested dictionaries.

PYEKX-8be01ef0

Count Frequencies of Elements

Problem

Write a function freq_map(lst) that returns frequency of elements in a list using a dictionary.

Example

freq_map(['a', 'b', 'a'])
# Output: {'a': 2, 'b': 1}

Why?

  • Foundational for log analysis, NLP, and aggregation pipelines.
  • Used in dashboards, tag clouds, voting systems.
  • Also forms the basis of histograms and feature vectors.

Pro Constraints

  • Do not use collections.Counter.
  • Bonus: Make function case-sensitive toggle via case_sensitive=True.

PYEKX-4ffdfbd7

Nested Key Lookup

Problem

Write nested_get(d, keys) where keys is a list like ['a', 'b', 'c'] that returns d['a']['b']['c'].

Example

nested_get({'a': {'b': {'c': 42}}}, ['a', 'b', 'c'])
# Output: 42

Why?

  • Vital in parsing JSON, API responses, settings files.
  • Common in recursive data structures, permission systems.
  • Avoids KeyError and nested try blocks.

Pro Constraints

  • Must not crash on missing keys.
  • Return None or optional default value.
  • Must work with arbitrary depth.

PYEKX-2d3191a8

Top N Frequent Elements

Problem

Write top_n_frequent(lst, n) to return top n most frequent items.

Example

top_n_frequent(['x', 'y', 'x', 'z'], 2)
# Output: [('x', 2), ('y', 1)]

Why?

  • Used in autocomplete, search trends, error analysis.
  • Found in ecommerce (top sold items), NLP (most used terms), and telemetry.
  • Teaches sorting dicts by value and memory-efficient counting.

Pro Constraints

  • No third-party modules.
  • Handle ties deterministically (alphabetical or insertion).
  • Bonus: Make output format toggleable (dict or list of tuples).