# Dictionary Exercises

2/10/2020

library(reticulate)

# Ex1

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

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

# Ex2

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

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

# Ex3

Remove Joe from the dictionary and print the new dictionary.

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

# Ex4

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

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

# Ex5

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

sum = 0
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?

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

# Ex7

Can you iterate over rti?

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

# Ex8

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

print(rti)
# This will fail

# Ex9

Can you convert rti to a list using the list() function? Can you retrieve items from this list with a numerical index?

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

# Ex10

Use the method keys() to extract something called my_keys from the dictionary. What is it? What is it’s type? Can you iterate over it? Can you use a numerical index? Can you convert it to a list?

my_keys = adict.keys()
print(my_keys)
## dict_keys(['Dick', 'harry', 'Tom'])
type(my_keys)
## <class 'dict_keys'>
for k in my_keys:
print(k, type(k))
# print(my_keys) This fails
## Dick <class 'str'>
## harry <class 'str'>
## Tom <class 'str'>
my_keys_l = list(my_keys)
type(my_keys_l)
## <class 'list'>

# Ex11

Use the method values() to extract something called my_keys from the dictionary. What is it? What is it’s type? Can you iterate over it? Can you use a numerical index? Can you convert it to a list?

my_vals = adict.values()
print(my_vals)
## dict_values([150, 180.0, 190])
type(my_vals)
## <class 'dict_values'>
for k in my_vals:
print(k, type(k))
# print(my_vals) This fails
## 150 <class 'int'>
## 180.0 <class 'float'>
## 190 <class 'int'>
my_vals_l = list(my_vals)
type(my_vals_l)
## <class 'list'>