3) d. Dictionary Examples




Domenico Telefonopoulos is taking his car-selling business seriously and organizes his clientele. He needs to store in a structured way all of his clients’ names and IDs, as pairs, in a Python dictionary. Initiate a dictionary (call it ddict) in Python then add two example names (Alice, Bob) which are the keys of the dictionary, with an ID each (1, 2), which are the values.

1
2
Output:
{'Alice': 1, 'Bob ': 2}




Domenico does not give up. He wants to have an entry for the married couples and now tries a tuple instead of a list:
>>> ddict[(‘Alice’, ‘Bob’)] = 33
What will the result of that be?

1
2
Output:
{'Alice': 1, 'Bob ': 2, ('Alice', 'Bob'): 33}




Now Domenico’s life is better and much more organized. He can print any client’s ID just by using his brand new dictionary. How exactly can he print the ID (value) for a given name (key)?

1
2
3
4
Output:
Alice = 1
Bob = 2
('Alice', 'Bob') = 33




Domenico has been trying to obtain an old client’s ID that hasn’t seen in a while. His name was John, Johny or maybe Johnnie. He is not sure. Which dictionary method is more suitable for Domenico in that case so as to avoid an error in Python?

1
2
3
4
Output:
John = None
Johny = None
Johnnie = 33




As time goes by, news clients arrive and (very) old customers must be removed. Write a Python code that deletes entries of the dictionary for particular keys. Can you delete entries from a dictionary?

1
2
3
4
5
Output:
Existing dictionary =  {'Alice': 1, 'Bob': 2, 'Johnnie': 33}
Existing dictionary =  {'Bob': 2, 'Johnnie': 33}
Existing dictionary =  {'Johnnie': 33}
Existing dictionary =  {}




Domenico has carelessly typed 6069 for the ID of ‘Charlie’ instead of 6969. Correct the error!

1
2
Output:
Corrected dictionary =  {'Alice': 1, 'Bob': 2, 'Johnnie': 33, 'Charlie': 6969}




Even worse, Domenico’s apprentice has mistyped the name of their biggest client! Add a key ‘Mr. Nomey’ with ID: 100 to ‘Mr. Money’. How many ways can you think of doing so?

1
2
Output:
{'Alice': 1, 'Bob': 2, 'Mr. Money': 33}




Arletta has been also compiling her dictionary! But they both need one a single one that contains all the information. Help them merge the two dictionaries in one.

1
2
Output:
{'Alice': 1, 'Bob': 2, 'Mr. Nomey': 33, 'Johnnie': 33, 'Charlie': 6969}




Domenico and Arletta are worried about the number of clients they have. Help them calculate it by finding the length of their dictionary.

1
2
3
Output:
The size of the dictionary is
5