CMPT 120 Lecture 24: Part 3: Dictionaries

51 views2 pages
meghan78 and 39786 others unlocked
CMPT 120 Full Course Notes
29
CMPT 120 Full Course Notes
Verified Note
29 documents

Document Summary

Creating empty dictionary & using for loop to iterate over. To create an empty dictionary: either use { } or use built-in function dict() empty_dict = { } or, another_empty_dict = dict() We can add elements to the dictionary as program executes, Use a for loop to iterate over a dictionary. For example: country_population = { canada" : 36624199, usa" : 324459463, mexico" : 129163276} for key in country_population: print(key) Some dictionary methods clear() method: deletes all the elements in a dictionary, leaving it empty. Format: dictionary_name. clear() get() method: gets you a value associated with specified the specified key. Default is returned if the key is not found. print(country_population. get( china", no value found")) Cannot raise keyerror exception. items() method: returns all the dictionaries keys and associated values. Each element in dictionary view is a tuple which contains a key and its associated value. Use a for loop to iterate over the tuples in the sequence.

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Documents