Working with Lists and Dictionaries
Dictionary methods and programs
Count characters with a dictionary.
Functions and methods for dictionaries:
- len(dict1): the number of key: value pairs.
- dict(): builds a dictionary from a sequence of (key, value) pairs: dict([('Mohan', 95), ('Ram', 89)]).
- keys(), values(), items(): give the keys, the values, and the (key, value) pairs (as dict_keys, dict_values and dict_items views).
- get(key): returns the key's value, or None if the key is absent, without an error.
- update(dict2): adds dict2's key: value pairs to the dictionary (dict2 itself is unchanged).
- clear(): deletes all items, leaving {}.
- del dict1[key] deletes one item; del dict1 deletes the whole dictionary, after which using dict1 gives a NameError.
Book examples with a dictionary ODD = {1:'One', 3:'Three', 5:'Five', 7:'Seven', 9:'Nine'}: len(ODD) is 5, 7 in ODD is True, 2 in ODD is False, ODD.get(9) is 'Nine', and del ODD[9] removes that item.
Programs:
- Program 4-4 reads names and salaries of employees into a dictionary (name as key, salary as value) and prints them as a table.
- Program 4-5 counts how many times each character appears in a string: for each character ch, if ch is already a key, add 1 to its count; otherwise set its count to 1. For 'HelloWorld', l appears 3 times and o twice.
- Program 4-6 turns a number into words using a dictionary from digits to names: each character is converted to an int and looked up, so 6512 becomes 'Six Five One Two'.
Example (new): with stock = {'pens': 40, 'pencils': 25}, stock.get('erasers') returns None instead of crashing, while stock['erasers'] would raise a KeyError; stock.update({'erasers': 10}) then adds it, making len(stock) equal to 3.
get() is the safe lookup: None, not KeyError.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.