Working with Lists and Dictionaries
Dictionaries
Look up and change a value by its key.
A dictionary is a mapping between a set of keys and a set of values. Each key: value pair is an item; items are separated by commas and enclosed in curly braces, with a colon between key and value. dict1 = {} is an empty dictionary.
- Keys must be unique and of an immutable type: a number, string or tuple (not a list). Values can repeat and be of any type.
- Items are accessed by key, not by position: with dict3 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}, dict3['Ram'] gives 89. A key that is not present gives a KeyError.
- In today's Python, dictionaries keep items in the order they were added.
Membership: in checks whether a key is present ('Suhel' in dict3 is True); not in checks that it is absent. These test keys, not values.
Dictionaries are mutable:
- Assigning to a new key adds an item: dict1['Meena'] = 78.
- Assigning to an existing key changes its value: dict1['Suhel'] = 93.5.
Traversing a dictionary:
- for key in dict1: print(key, ':', dict1[key])
- for key, value in dict1.items(): print(key, ':', value)
Example (new): with capitals = {'Kerala':'Thiruvananthapuram', 'Goa':'Panaji'}, capitals['Goa'] gives 'Panaji'; capitals['Sikkim'] = 'Gangtok' adds a new item; and 'Delhi' in capitals is False, since no such key exists.
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.