{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Cmput174 dic onaries 15 keys and values getkey returns

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: pairs to a Dic$onary • To add a new value, assign it to a new key • Dic-onaries do not need to use append() or insert() like lists do. CMPUT174  ­ ­ Dic-onaries 13 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" CMPUT174  ­ ­ Dic-onaries 14 Keys and values • A run-me error occurs if you try to access a dic-onary with a key which is not in it: • The get(key) method handles this error nicely: default parameter! CMPUT174  ­ ­ Dic-onaries 15 Keys and values • get(key) returns the value OR a default parameter: • To get all keys or all values in a dic-onary: CMPUT174  ­ ­ Dic-onaries 16 Membership tests • Checking if a key is in the dic-onary • To check if a value is in the dic-onary, we need to get the list of values first: CMPUT174  ­ ­ Dic-onaries 17 Dele$ng Pairs from a Dic$onary • There are two ways of removing pairs from a dic-onary CMPUT174  ­ ­ Dic-onaries 18 Dele$ng Pairs from a Dic$onary • Using pop() on a list removes and returns the last element • Dic-onaries don’t have a “last” element, so popitem() removes and returns some key/value pair from a dic-onary • Using pop(key) on a dic-onary 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 dic-onary will return default if...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online