1.2.1.4 PCEP-30-02 Practice Test Compendium – Tuples and dictionaries

Dictionaries – continued

04) Accessing a dictionary's value requires the use of its key. For example, the following line outputs 911 to the screen:

print(phone_directory['Emergency'])

05) An attempt to access an element whose key is absent in the dictionary raises the KeyError exception.

06) The in and not in operators can be used to check whether a certain key exists in the dictionary. For example, the following line prints True False to the screen:

print('Emergency' in phone_directory, 'White House' in phone_directory)

07) The len() function returns the number of pairs contained in the directory. For example, the following line outputs 0 to the screen:

print(len(empty_directory))

08) Changing a value of the existing key is done by an assignment. For example, the following snippet outputs False to the screen:

attendance = {'Bob': True}
attendance['Bob'] = False
print(attendance['Bob'])

09) Adding a new pair to the dictionary resembles a regular assignment. For example, the following snippet outputs 2 to the screen:

domains = {'au': 'Australia'}
domains['at'] = 'Austria'
print(len(domains))

10) Removing a pair from a dictionary is done with the del instruction. For example, the following snippet outputs 0 to the screen:

currencies = {'USD': 'United States dollar'}
del currencies['USD']
print(len(currencies))

11) When iterated through by the for loop, the dictionary displays only its keys. For example, the following snippet outputs A B to the screen:

phonetic = {'A': 'Alpha', 'B': 'Bravo'}
for key in phonetic:
    print(key, end=' ')

12) The .keys() method returns a list of keys contained in the dictionary. For example, the following snippet outputs A B to the screen:

phonetic = {'A': 'Alpha', 'B': 'Bravo'}
for key in phonetic.keys():
    print(key, end=' ')

13) The .values() method returns a list of values contained in the dictionary. For example, the following snippet outputs Alpha Bravo to the screen:

phonetic = {'A': 'Alpha', 'B': 'Bravo'}
for value in phonetic.values():
    print(value, end=' ')

14) The .items() method returns a list of two-element tuples, each filled with key:value pairs. For example, the following snippet outputs ('A', 'Alpha') ('B', 'Bravo') to the screen:

phonetic = {'A': 'Alpha', 'B': 'Bravo'}
for item in phonetic.items():
    print(item, end=' ')

Last updated