clear()
方法从字典中移除所有项目。
示例
# dictionary
numbers = {1: "one", 2: "two"}
# removes all the items from the dictionary
numbers.clear()
print(numbers)
# Output: {}
clear() 语法
clear()
方法的语法是
dictionary.clear()
在这里,clear()
移除字典中存在的所有项目。
clear() 参数
clear()
方法不接受任何参数。
clear() 返回值
clear()
方法不返回任何值。
示例 1:Python 字典 clear()
cityTemperature = {"New York": 18, "Texas": 26}
print("Dictionary before clear():", cityTemperature)
# removes all the items from the dictionary
cityTemperature.clear()
print("Dictionary after clear():", cityTemperature)
输出
Dictionary before clear(): {'New York': 18, 'Texas': 26} Dictionary after clear(): {}
在上面的示例中,我们使用 clear()
方法从字典 cityTemperature 中移除了所有项目。
在这里,该方法从 {"New York": 18, "Texas": 26}
中移除了所有项目,并返回一个空字典 {}
。
另请阅读