dictionaries last half of chapter 5. dictionary a sequence of key-value pairs – key is usually a...

5
Dictionaries Last half of Chapter 5

Upload: godwin-mcbride

Post on 17-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a string or integer – Value can be any python object There

Dictionaries

Last half of Chapter 5

Page 2: Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a string or integer – Value can be any python object There

Dictionary

• A sequence of key-value pairs– Key is usually a string or integer– Value can be any python object

• There is no order to the elements– So, there isn't a first or a last element– Python uses its own algorithm to order elements

(for efficient access)• You access values by using the key.

Page 3: Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a string or integer – Value can be any python object There

Dictionary operations

• Creating an empty dictionary:D = {}

• Creating a dictionary with string-float pairsD2 = {"ABC":42.9, "DEF":13.8, "GHI":-19.1}

• Getting a list of keys or valuesD2.keys() # Returns ["ABC", "GHI", "DEF"] or something like this.

• Getting a list of valuesD2.values() # Returns [42.9, -19.1, 13.8]

Page 4: Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a string or integer – Value can be any python object There

Dictionary Index'ing

• Using an existing elementprint(D2["ABC"])

• Changing a value for an existing keyD2["ABC"] = 100.3

• Adding a new valueD2["XYZ"] = 0.0

Note how this looks the same as modifying.

Page 5: Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a string or integer – Value can be any python object There

Dictionary examples

• [Using integers as a key]• [Reiner Tile Sets…]