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.
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.
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.
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.
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.
{'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.
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.
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | ATGGCC | {'A': 1, 'C': 2, 'G': 2, 'T': 1} |
| 2 | stdin | AAAA | {'A': 4, 'C': 0, 'G': 0, 'T': 0} |
| 3 | stdin | GC | {'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.