Dictionary Flashcards
Definition of dictionary
A dictionary consists of keys and values. It is helpful to compare a dictionary to a list. Instead of the numerical indexes such as a list, dictionaries have keys. These keys are the keys that are used to access values within a dictionary
Sample dictionary
In summary, like a list, a dictionary holds a sequence of elements. Each element is represented by a key and its corresponding value. Dictionaries are created with two curly braces containing keys and values separated by a colon. For every key, there can only be one single value, however, multiple keys can hold the same value. Keys can only be strings, numbers, or tuples, but values can be any data type.
release_year_dict = {“Thriller”: “1982”, “Back in Black”: “1980”, \
“The Dark Side of the Moon”: “1973”, “The Bodyguard”: “1992”, \
“Bat Out of Hell”: “1977”, “Their Greatest Hits (1971-1975)”: “1976”, \
“Saturday Night Fever”: “1977”, “Rumours”: “1977”}
release_year_dict
Answer: {'Thriller': '1982', 'Back in Black': '1980', 'The Dark Side of the Moon': '1973', 'The Bodyguard': '1992', 'Bat Out of Hell': '1977', 'Their Greatest Hits (1971-1975)': '1976', 'Saturday Night Fever': '1977', 'Rumours': '1977'}
Retrieve all the keys
release_year_dict.keys( )
dict_keys([‘Thriller’, ‘Back in Black’, ‘The Dark Side of the Moon’, ‘The Bodyguard’, ‘Bat Out of Hell’, ‘Their Greatest Hits (1971-1975)’, ‘Saturday Night Fever’, ‘Rumours’])
Retrieve all the values
release_year_dict.values( )
dict_values([‘1982’, ‘1980’, ‘1973’, ‘1992’, ‘1977’, ‘1976’, ‘1977’, ‘1977’])
Add an entry
release_year_dict['Graduation'] = '2007' release_year_dict {'Thriller': '1982', 'Back in Black': '1980', 'The Dark Side of the Moon': '1973', 'The Bodyguard': '1992', 'Bat Out of Hell': '1977', 'Their Greatest Hits (1971-1975)': '1976', 'Saturday Night Fever': '1977', 'Rumours': '1977', 'Graduation': '2007'}