Python Basics04/13
Starting sandbox…
Beginner·3 graded tests

Dictionaries

A dictionary maps keys to values. Lookup by key takes approximately constant time regardless of the dictionary's size, which makes a dictionary the correct structure whenever data is retrieved by name or identifier rather than by position.

Keys must be hashable, which in practice means immutable: strings, numbers and tuples are valid keys, and lists are not. Values may be of any type. Since Python 3.7, dictionaries preserve insertion order.

[1]python
out1ms
120 3

Reading values safely

Indexing a key that is not present raises KeyError. The get method returns None instead, or a supplied default. Use get when absence is an expected condition, and indexing when absence indicates a defect in the data.

[2]python
out1ms
None
0
False

The in operator tests for the presence of a key, not a value. Testing membership against depths.values() is possible but requires a linear scan and is rarely what is wanted.

Adding, updating and removing

Assignment to a key either inserts a new entry or replaces an existing one; there is no separate insert operation. del removes an entry and raises KeyError if the key is absent. pop removes and returns a value, and accepts a default.

[3]python
out1ms
45 {'TP53': 130}

Iteration

Iterating a dictionary directly yields its keys. values() yields the values and items() yields key-value pairs, which unpack naturally in a for statement. This is the standard way to walk a mapping.

[4]python
out1ms
TP53      120
BRCA1      88

Counting

Accumulating counts in a dictionary is a common operation. Using get with a default of zero removes the need to test whether a key already exists.

[5]python
out1ms
{'A': 3, 'T': 4, 'G': 3, 'C': 2}

The standard library provides collections.Counter for this purpose, which is both shorter and faster. The manual form is shown first because the same pattern applies to accumulations that Counter does not cover, such as summing values or collecting lists.

[6]python
out1ms
Counter({'T': 4, 'A': 3, 'G': 3, 'C': 2})

Task

Write base_counts(sequence). Return a dictionary giving the number of occurrences of each of A, C, G and T. All four keys must be present even when the count is zero, and they must appear in the order A, C, G, T. Characters other than these four are ignored.

Initialise the dictionary with all four keys before counting: this guarantees both their presence and their order, since dictionaries preserve insertion order.

exerciseEvery submission runs independently in a fresh namespace.

Test cases · 3

#viainputexpected stdout
1stdinATGGCC{'A': 1, 'C': 2, 'G': 2, 'T': 1}
2stdinAAAA{'A': 4, 'C': 0, 'G': 0, 'T': 0}
3stdinGC{'A': 0, 'C': 1, 'G': 1, 'T': 0}

Hints · 2

01Hint

Start with a dictionary that already has all four keys set to 0.

02Hint

Insertion order is preserved, so build the dict in A, C, G, T order.