An introduction to dictionaries - answers
Q1. What kind of brackets do you use for lists, tuples and dictionaries?
Lists = [ ] Tuples = ( ) Dictionaries = { }
Q2. Get the above dictionary working in Python.
Q3. Add code to add the following acromyms:
WWW : World Wide Web
WAN : Wide Area Network
VGA : Video Graphics Array
Check it works.
acroynms['WWW'] = 'World Wide Web'
acroynms['WAN'] = 'Wide Area Network'
acroynms['VGA'] = 'Video Graphics Array'
Q4. Add code to delete the entries for RAM and ROM and then check it works correctly.
del acroynms['RAM']
del acroynms['ROM']
Q5. Write code using the in operator to check to see if LAN is in the dictionary.
if 'LAN' in acroynms:
print('Exists!')
else:
print('Does not exist!')
Q6. Use the get method to get back the values for ALU and WEP. Display a suitable default message if either isn't in the dictionary.
print(acroynms.get('ALU', 'Sorry! That is not in the dictionary'))
print(acroynms.get('WEP', 'Sorry! That is not in the dictionary'))
Q7. Find and use three other methods associated with a dictionary object.
Suitable example might include:
print(acroynms.keys()) # returns only the keys
print('')
print(acroynms.values()) # returns only the values
print('')
print(acroynms.items()) # returns all the items
Q8. How would you create an empty dictionary called capitals?
capitals = {}