Dicts 1

Harold Nelson

9/30/2020

Ex1

Create a dictionary to record the weights of Joe (175), Tom (190), and Dick (150). Print the dictionary.

Answer

adict = {"Joe":175,"Tom":190,"Dick":150}
print(adict)
## {'Joe': 175, 'Tom': 190, 'Dick': 150}

Ex2

Add Harry, who weighs 180 pounds to the dictionary and print the new dictionary.

Answer

adict["harry"] = 180.
print(adict)
## {'Joe': 175, 'Tom': 190, 'Dick': 150, 'harry': 180.0}

Ex3

Remove Joe from the dictionary and print the new dictionary.

Answer

del adict["Joe"]
print(adict)
## {'Tom': 190, 'Dick': 150, 'harry': 180.0}

Ex4

Use the dict to look up Dick’s weight and print it.

Answer

print(adict["Dick"])
## 150

Ex5

Iterate over the items in the dictionary and calculate the sum of the weights. Print the sum.

Answer

sum = 0
for thing in adict:
    sum = sum + adict[thing]
print(sum)    
## 520.0

Ex6

Use the method items() to get the items in adict. Print the rti, the object returned by the items() method. What is the type of this object?

Answer

rti = adict.items()
print(rti)
## dict_items([('Tom', 190), ('Dick', 150), ('harry', 180.0)])
type(rti)
## <class 'dict_items'>

Ex7

Can you iterate over rti?

Answer

for i in rti:
    print(i)
    print(type(i))
## ('Tom', 190)
## <class 'tuple'>
## ('Dick', 150)
## <class 'tuple'>
## ('harry', 180.0)
## <class 'tuple'>

Ex8ti

Can you use an integer index to obtain one of the things in rti?

Answer

print(rti[0])

Ex9

Can you convert rti to a list using the list() function?

Answer

rti_l = list(rti)
print(rti_l)
## [('Tom', 190), ('Dick', 150), ('harry', 180.0)]
type(rti_l)
## <class 'list'>
print(rti_l[0])
## ('Tom', 190)