3️⃣

9.3 Retrieving, Updating, and Adding Values

Retrieving, Updating, and Adding Values

Unlike lists, dictionaries do not have indices. You access values using their keys. For example, if I wanted to get the address of "Daisy Johnson", I would do this:

daisy_address = contacts["Daisy Johnson"]
print(daisy_address)  # prints “1357 Wall St”

Similarly, if I wanted to update the address of "Daisy Johnson", I would do this:

contacts["Daisy Johnson"] = "2468 Park Ave"
print(contacts["Daisy Johnson"])  # prints “2468 Park Ave”

To add a new key-value pair, simply use the same syntax for updating a key-value pair:

contacts["Leo Fitz"] = "1258 Monkey Dr"
print(contacts)  # prints the dictionary with the new entry

View code on GitHub.

Output of the code above:

1357 Wall St
2468 Park Ave
{'John Doe' : '1234 Main St', 'Jane Smith' : '5678 Market St',
'Daisy Johnson' : '2468 Park Ave', 'Leo Fitz' : '1258 Monkey Dr'}

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.