在本文中,我们考虑一个字典,其中的值以列表形式出现。然后,我们考虑从列表中清除这些值。我们在这里有两种方法。一种是使用清除方法,另一种是使用列表推导为每个键指定空值。
x1 = {"Apple" : [4,6,9,2],"Grape" : [7,8,2,1],"Orange" : [3,6,2,4]} x2 = {"mango" : [4,6,9,2],"pineapple" : [7,8,2,1],"cherry" : [3,6,2,4]} print("The given input is : " + str(x1)) # using loop + clear()for k in x1: x1[k].clear() print("Clearing list as dictionary value is : " + str(x1)) print("\nThe given input is : " + str(x2)) # using dictionary comprehension x2 = {k : [] for k in x2} print("Clearing list as dictionary value is : " + str(x2))
输出结果
运行上面的代码给我们以下结果-
The given input is : {'Apple': [4, 6, 9, 2], 'Grape': [7, 8, 2, 1], 'Orange': [3, 6, 2, 4]} Clearing list as dictionary value is : {'Apple': [], 'Grape': [], 'Orange': []} The given input is : {'mango': [4, 6, 9, 2], 'pineapple': [7, 8, 2, 1], 'cherry': [3, 6, 2, 4]} Clearing list as dictionary value is : {'mango': [], 'pineapple': [], 'cherry': []}