print(d["b"])

print(d["b"] + d["a"])

It's as easy as that. However, if you want to do the sum of all dictionary values you need to take another approach instead of accessing all values one by one. We're going through that approach later on in another exercise.


There is no key Smith in the dictionary. Smith is a value. You want to use Surname if you want to access Smith :

print(d["Surname"])

A KeyError always means Python could not find a key with the name shown next to KeyError (e.g. Smith ).


d = {"a": 1, "b": 2} d["c"] = 3 print(d) Explanation: Adding pairs of keys and values is straightforward as you can see. Note though that you cannot fix the order of the dictionary items. Dictionaries are unordered collections of items.

d = {"a": 1, "b": 2, "c": 3} print(sum(d.values())) Explanation: d.values() returns a list-like dict_values object while the sum function calculates the sum of the dict_values items.

d = {"a": 1, "b": 2, "c": 3} d = dict((key, value) for key, value in d.items() if value <= 1) print(d) Explanation: Here we're using a dictionary comprehension. The comprehension is the expression inside dict() . The comprehension iterates through the existing dictionary items and if an item is less or equal to 1,the item is added to a new dict. This new dict is assigned to the existing variable d so we end up with a filtered dictionary in d.

from pprint import pprint d = dict(a = list(range(1, 11)), b = list(range(11, 21)), c = list(range(21, 31))) print(d) Explanation: We're using ranges here to construct the lists. We're also using the built-in Python pprint module which is used to print out well formatted views of datatypes in Python.

from pprint import pprint d = dict(a = list(range(1, 11)), b = list(range(11, 21)), c = list(range(21, 31))) print(d['b'][2])

d = dict(a = list(range(1, 11)), b = list(range(11, 21)), c = list(range(21, 31))) for key, value in d.items(): print(key, "has value", value)

import string for letter in string.ascii_lowercase: print(letter) Explanation: string is a built-in module and string.ascii_lowercase returns a string object containing all 26 letters of English alphabet. Then we simply iterate through that string and print out the string items.

for i in range(1,11): print(i) Explanation: A for loop is used to repeat an action (i.e. print ) until the iterating sequence (i.e. range ) is consumed. In our case it would print all items of the range one by one.


Line 4 throws a TypeError because Python cannot multiply a None type object with an integer. The function output is what produces a None object because the function definition is not returning anything. Fix it by using return instead of print :

Image You can then test your solution by passing 2 for h and you should get the expected output. Expected output: 4071.5040790523717 Expected output: 4071.5040790523717