Python uses hashing on the keys to store the dic

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: dices is cumbersome (and error ­prone) • A dic-onary associates values (e.g., speeds) with other values (e.g., plane names)   Without indices! CMPUT174  ­ ­ Dic-onaries 6 Dic$onaries • Dic-onaries store key : value pairs • Keys must be immutable objects!   Python uses hashing on the keys to store the dic-onary (this just means that they can’t be something that changes) • Values can be anything (mutable or immutable objects) CMPUT174  ­ ­ Dic-onaries 7 Crea$ng dic$onaries • As with lists, we can create dic-onaries in different ways 1.  Using a mapping of key:value pairs 2.  Star-ng with an empty dic-onary 3.  Popula-ng from an iterable (like a list) with keys and values CMPUT174  ­ ­ Dic-onaries 8 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  ­ ­ Dic-onaries 9 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, dic-onaries do not have a method for adding pairs • NOTE: D = {} means an empty dic-onary in Python CMPUT174  ­ ­ Dic-onaries 10 Crea$ng a dic$onary from iterables • Python will create a dic-onary from an iterable containing key, value pairs too • Example: building a dic-onary from a list of pairs CMPUT174  ­ ­ Dic-onaries 11 Referencing Values • Reference to the value of a given key: • In dic-onaries, 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  ­ ­ Dic-onaries 12 Adding key/value...
View Full Document

This document was uploaded on 03/02/2014.

Ask a homework question - tutors are online