PROJECT SOURCE
test_dictionaries.py
下载资料/01-Python/src/data_types/test_dictionaries.py
配套学习源码,可下载后在本机运行。
# Selected and shortened from Oleksii Trekhleb / learn-python.
# MIT license: ../../LICENSE. Modified 2026-11-08; see download manifest.
def test_dictionary():
"""Dictionary"""
fruits_dictionary = {
'cherry': 'red',
'apple': 'green',
'banana': 'yellow',
}
assert isinstance(fruits_dictionary, dict)
# You may access set elements by keys.
assert fruits_dictionary['apple'] == 'green'
assert fruits_dictionary['banana'] == 'yellow'
assert fruits_dictionary['cherry'] == 'red'
# To check whether a single key is in the dictionary, use the in keyword.
assert 'apple' in fruits_dictionary
assert 'pineapple' not in fruits_dictionary
# Change the apple color to "red".
fruits_dictionary['apple'] = 'red'
# Add new key/value pair to the dictionary
fruits_dictionary['pineapple'] = 'yellow'
assert fruits_dictionary['pineapple'] == 'yellow'
# Performing list(d) on a dictionary returns a list of all the keys used in the dictionary,
# in insertion order (if you want it sorted, just use sorted(d) instead).
assert list(fruits_dictionary) == ['cherry', 'apple', 'banana', 'pineapple']
assert sorted(fruits_dictionary) == ['apple', 'banana', 'cherry', 'pineapple']
# It is also possible to delete a key:value pair with del.
del fruits_dictionary['pineapple']
assert list(fruits_dictionary) == ['cherry', 'apple', 'banana']
if __name__ == "__main__":
test_dictionary()
print("PASS")