Cmput174 dic2onaries 15 5 131029 keys and values

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 12 4 13 ­10 ­29 Adding key/value pairs to a Dic$onary • To add a new value, assign it to a new key • Dic2onaries do not need to use append() or insert() like lists do. 13 CMPUT174  ­ ­ Dic2onaries Upda$ng a Value in a Dic$onary • To update a value, re ­assign it • You can change the value associated with a key by re ­ assigning • For example: my_dict = {“greeting”:”Hello”}
 print(my_dict[“greeting”]) # outputs Hello
 my_dict[“greeting”] = “Hi”
 print(my_dict[“greeting”]) # outputs Hi" 14 CMPUT174  ­ ­ Dic2onaries Keys and values • A run2me error occurs if you try to access a dic2onary with a key which is not in it: • The get(key) method handles this error nicely: default parameter! CMPUT174  ­ ­ Dic2onaries 15 5 13 ­10 ­29 Keys and values • get(key) returns the value OR a default parameter: • To get all keys or all values in a dic2onary: CMPUT174  ­ ­ Dic2onaries 16 Membership tests • Checking if a key is in the dic2onary • To check if a value is in the dic2onary, we need to get the list of values first: CMPUT174  ­ ­ Dic2onaries 17 Dele$ng Pairs from a Dic$onary • There are two ways of removing pairs from a dic2onary CMPUT174  ­ ­ Dic2onaries 18 6 13 ­10 ­29 Dele$ng Pairs from a Dic$onary  Using pop() on a list removes and returns the last element • Dic2onaries don’t have a “last” element, so popitem() removes and returns some key/value pair from a dic2onary • Using pop(key) on a dic2onary requires an argument which is the key to remove. If the key exists, it is removed and the value is returned. If it does not, an error occurs. • Using pop(key, default) on a dic2o...
View Full Document

Ask a homework question - tutors are online