Lecture11-Dictionaries

# Appendx appends x to end linserti x inserts x before

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

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: the key does not exist, and so no error occurs. CMPUT174  ­ ­ Dic-onaries 19 Example: dele\$ng pairs returned key: value pair key returned value CMPUT174  ­ ­ Dic-onaries 20 Itera\$ng over Dic\$onaries • There are two common ways of itera-ng over the whole dic-onary: 1.  For loop over the keys, and using the keys to access the values 2.  For loop over key:value pairs CMPUT174  ­ ­ Dic-onaries 21 Looping over Keys • For loop over the keys, and using the keys to access the values: CMPUT174  ­ ­ Dic-onaries 22 Looping over Key/Value Pairs • items() returns a list of pairs of key/values in a dic-onary • For loop over the key:value pairs: CMPUT174  ­ ­ Dic-onaries 23 Itera\$ng over Dic\$onaries • Of course, we can iterate over all keys or all values as well: CMPUT174  ­ ­ Dic-onaries 24 Comparison with lists Lists Elements New empty list Dictionaries Any Python object can go in a list key:value pairs where the keys must be immutable objects L= D={} Element access L[ i ] – returns element at index i Adding new elements L.append(x) – appends x to end L.insert(i, x) – inserts x before index i Updating element L[ i ] = y (index i must be in range) Removing elements L.pop( i ) – removes and returns item at index i L.remove(x) – removes first occurrence of x CMPUT174  ­ ­ Dic-onaries D[k] – returns the value associated with key k D[k] = v – updates the value of key k or adds the pair k:v if k is not in used in D D.pop( k) – removes key:value pair (k,v) and returns v D.popitem() – removes and returns a key:value pair (k,v) 25 How are dic\$onaries implemented? • Dic-onaries are implemented using hashing. The keys are hashed using a hashing func-on. For this reason, Python requires that the keys be immutable although the values can be anything • Because hashing is used, the order in which the key/value pairs are added is not preserved by the dic-onary   Data structures such as sets a...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online