CMPT 120 Lecture 24: Part 2: Dictionaries

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

Document Summary

To retrieve a specific value, use the key associated with it. General format to retrieve a from a dictionary: dictionary_name[key] If key is in the dictionary, associated value is returned, otherwise, keyerror exception is raised. To test whether a key is in a dictionary use the in and not in operators. These operators can helps prevent keyerror exceptions. #36624199, 324459463 = value country_population = { canada" : 36624199, usa" : 324459463} print(country_population[canada]) print({:,}. format(country_population[usa])) print(country_population]) To add a new key-value pair: dictionary_name[key] = value. If key exists in the dictionary, the value associated with it will be changed. Else, added. country_population = { canada" : 36624199, usa" : 324459463} country_population[ mexico"] = 129163276 print(country_population) { canada" : 36624199, usa" : 324459463, mexico" : 129163276} If key is not in the dictionary, keyerror exception is raised country_population = { canada": 36624199, usa": 324459463, mexico": 129163276} del country_population[ mexico"] print(country_population)

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