Lecture11-Dictionaries-3pp

Python uses hashing on the keys to store the

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: ula2ng indices is cumbersome (and error ­prone) • A dic2onary associates values (e.g., speeds) with other values (e.g., plane names)   Without indices! CMPUT174  ­ ­ Dic2onaries 6 2 13 ­10 ­29 Dic$onaries • Dic2onaries store key : value pairs • Keys must be immutable objects!   Python uses hashing on the keys to store the dic2onary (this just means that they can’t be something that changes) • Values can be anything (mutable or immutable objects) 7 CMPUT174  ­ ­ Dic2onaries Crea$ng dic$onaries • As with lists, we can create dic2onaries in different ways 1.  Using a mapping of key:value pairs 2.  Star2ng with an empty dic2onary 3.  Popula2ng from an iterable (like a list) with keys and values 8 CMPUT174  ­ ­ Dic2onaries Building a dic$onary from a mapping • Python calls a list of key:value pairs a mapping mapping • The key is to the lea of “:”, the value is to the right. CMPUT174  ­ ­ Dic2onaries 9 3 13 ­10 ­29 Crea$ng a dic$onary from an empty dic$onary • We add pairs by assigning values to keys start with an empty dictionary adding new pairs • Unlike lists and sets, dic2onaries do not have a method for adding pairs • NOTE: D = {} means an empty dic2onary in Python CMPUT174  ­ ­ Dic2onaries 10 Crea$ng a dic$onary from iterables • Python will create a dic2onary from an iterable containing key, value pairs too • Example: building a dic2onary from a list of pairs CMPUT174  ­ ­ Dic2onaries 11 Referencing Values • Reference to the value of a given key: • In dic2onaries, indexing like with lists will not work! • For example: my_dict = {“greeting”:“Hello!”}
 print(my_dict[“greeting”]) # prints Hello!
 print(my_dict[0]) # this will give an error!" CMPUT174  ­ ­ Dic2onaries...
View Full Document

Ask a homework question - tutors are online