sweigart chapter 5 Flashcards
dictionary
a mutable collection of many values. it is typed with braces {}. items are unordered and therefore cannot be sliced. there is no “first” item in a dictionary and it does not matter in what order the key-value pairs are typed.
keys
indexes for dictionaries. the indexes can use many different data types and do not have to start at 0. you can access values through their keys.
key-value pair
a key with its associated value.
dictionary methods
there are three dictionary methods that will return list-like values of the dictionary’s keys, values, or both keys and values; keys(), values(), and items(). the values returned are not true lists; they cannot be modified and do not have an append() method.
list() function
can be used if you want a true list.
in and not in operators
can also check whether a key or value exists in a dictionary.
get() method
takes two arguments; the key of the value to retrieve and a fallback value to return if that key does not exist. eg., if ‘eggs’ is not a key in the dictionary, the default value could be 0. without using this it would cause an error message.
setdefault() method
the first argument passed to the method is the key to check for and the second argument is the value to set at that key if the key does not exist. if they key does exist, the setdefault() method returns the key’s value. it is a shortcut to ensure a key exists.
pprint module
provides access to pprint() and pformat() function that will “pretty print” a dictionary’s values. it is helpful when you want a cleaner display of the items in a dictionary than what print() provides.
nested dictionaries and lists
dictionaries and lists that contain other dictionaries and lists. this may be necessary if a model gets more complicated. lists are useful to contain an ordered series of values, and dictionaries are useful for associating keys with values.