90 likes | 179 Views
Lecture 20. Dictionaries. What is a dictionary?. In a list we can identify an retrieve an item by its position or index. A dictionary uses key, value pairs. This association between a key and its value is called a mapping . Here is an example of a dictionary:
E N D
Lecture 20 Dictionaries
What is a dictionary? • In a list we can identify an retrieve an item by its position or index. • A dictionary uses key, valuepairs. This association between a key and its value is called a mapping. • Here is an example of a dictionary: • phoneList = {“Mary”: “276-5402”, “Jim”: “276-4106”, “Tom”: “378-9787”} • keys can be strings or integers • Values can be anything
Accessing a dictionary • phoneList = {“Mary”: “276-5402”, “Jim”: “276-4106”, “Tom”: “378-9787”} • >>print phoneList[“Mary”] • >> 276-5402 • Dictionaries are mutable – I can change the contents • >> phoneList[“Mary”] = “236-3435” • >> print phoneList[“Mary”] • >> 236-3435
Operations on a dictionary • You can print it, but it may not be in the same order as when you created it • >>> phoneList = {'Mary': "236-3435", "Jim":'276-4106', 'Tom': '378-9787'} • >>> print phoneList • {'Jim': '276-4106', 'Mary': '236-3435', 'Tom': '378-9787'}
To add to a Dictionary • Simply assign to a new or old key • >>> phoneList["Drew"] = "289-5667“ • >>> print phoneList • {'Jim': '276-4106', 'Mary': '236-3435', 'Drew': '289-5667', 'Tom': '378-9787'} • >>>
Dictionary Methods • Getting a list of all the keys or values in the dictionary • >>> phoneList.keys() • ['Jim', 'Mary', 'Drew', 'Tom'] • >>> phoneList.values() • ['276-4106', '236-3435', '289-5667', '378-9787']
Methods continued • Checking if a key is in the dictionary • >>> phoneList.has_key("Mary") • True • >>> 'Mary' in phoneList • True • >>> 'John' in phoneList • False
More methods • Getting all the pairs in the dictionary • >>> phoneList.items() • [('Jim', '276-4106'), ('Mary', '236-3435'), ('Drew', '289-5667'), ('Tom', '378-9787')] • Another way to get a value if you don’t know it is in the dictionary • >>> phoneList.get("Mary", "No phone") • '236-3435' • >>> phoneList.get("John", "No phone") • 'No phone'
Removing from a dictionary • >>> del phoneList["Mary"] • >>> print phoneList • {'Jim': '276-4106', 'Drew': '289-5667', 'Tom': '378-9787'} • >>> phoneList.clear() • phoneList still exists but you have removed all the pairs.