Lecture11-Dictionaries-3pp

Appendx appends x to end linserti x inserts x before

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: nary will return default if the key does not exist, and so no error occurs. 19 CMPUT174  ­ ­ Dic2onaries Example: dele$ng pairs returned key: value pair key returned value CMPUT174  ­ ­ Dic2onaries 20 Itera$ng over Dic$onaries • There are two common ways of itera2ng over the whole dic2onary: 1.  For loop over the keys, and using the keys to access the values 2.  For loop over key:value pairs CMPUT174  ­ ­ Dic2onaries 21 7 13 ­10 ­29 Looping over Keys • For loop over the keys, and using the keys to access the values: CMPUT174  ­ ­ Dic2onaries 22 Looping over Key/Value Pairs • items() returns a list of pairs of key/values in a dic2onary • For loop over the key:value pairs: CMPUT174  ­ ­ Dic2onaries 23 Itera$ng over Dic$onaries • Of course, we can iterate over all keys or all values as well: CMPUT174  ­ ­ Dic2onaries 24 8 13 ­10 ­29 Comparison with lists Lists Elements Dictionaries Any Python object can go in a list key:value pairs where the keys must be immutable objects New empty list 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 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 CMPUT174  ­ ­ Dic2onaries How are dic$onaries implemented? • Dic2onaries are implemented using hashing. The keys are hashed using a hashing func2on. 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 dic2onary...
View Full Document

Ask a homework question - tutors are online