Видеокурс выложен на сайте Altube.ru вместо Youtube и плеер Altube не поддерживает субтитры. Прошу решить вопрос о предоставлении русских субтитров в этом англоязычном видеокурсе. |
Словари
19.3. Циклы и словари
Если вы используете словарь как последовательность (sequence) в операторе for, происходит обход ключей словаря. Например, print_hist выводит на экран каждый ключ и соответствующее ему значение:
def print_hist(h): for c in h: print c, h[c]
Результат имеет следующий вид:
>>> h = histogram('parrot') >>> print_hist h a 1 p 1 r 2 t 1 o 1
Снова ключи не имеют порядка.
Если вы хотите вывести на экран ключи в алфавитном порядке, сначала составьте список ключей в словаре с помощью метода словаря keys, затем отсортируйте этот список и в цикле, просматривая каждый ключ, выводите на экран пару ключ/значение, как показано далее:
def print_sorted_hist(h): lst = h.keys() lst.sort() for c in lst: print c, h[c]
Результат будет следующий:
>>> h = histogram('parrot') >>> print_sorted_hist(h) a 1 o 1 p 1 r 2 t 1
Теперь ключи отсортированы в алфавитном порядке.
9.6. Словарь
dictionary: A mapping from a set of keys to their corresponding values.
hashtable: The algorithm used to implement Python dictionaries.
hash function: A function used by a hashtable to compute the location for a key.
histogram: A set of counters.
implementation: A way of performing a computation.
item: Another name for a key-value pair.
key: An object that appears in a dictionary as the first part of a key-value pair.
key-value pair: The representation of the mapping from a key to a value.
lookup: A dictionary operation that takes a key and finds the corresponding value.
nested loops: When there is one or more loops "inside" of another loop. The inner loop runs to completion each time the outer loop runs once.
value: An object that appears in a dictionary as the second part of a key-value pair.
This is more specific than our previous use of the word "value."