Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a...
-
Upload
godwin-mcbride -
Category
Documents
-
view
214 -
download
1
Transcript of Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a...
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 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.
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]
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.
Dictionary examples
• [Using integers as a key]• [Reiner Tile Sets…]