Tuples and Dictionaries
Dictionaries
Create a dictionary and look up a value.
A dictionary is a mapping from keys to values. Each key : value pair is an item; items are separated by commas and enclosed in curly braces:
- marks = {'Asha': 91, 'Ravi': 78, 'Kiran': 85}
Keys must be unique and immutable: a number, a string or a tuple (never a list). Values can be of any type, and can repeat.
An empty dictionary is made with {} or dict().
Items are reached by their key, not by a position: marks['Asha'] is 91. Asking for a key that is not there gives a KeyError.
Dictionaries are mutable:
- Assigning to a new key adds an item: marks['Neha'] = 88.
- Assigning to an existing key changes its value: marks['Ravi'] = 80.
Python keeps the items in the order in which they were added. (The book's section 10.7 says so; its Summary still calls dictionaries 'unordered', which is out of date.)
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.