开发者社区> 问答> 正文

Python 移除字典点键值(key/value)对

Python 移除字典点键值(key/value)对

展开
收起
游客ejnn55cgkof5g 2020-02-14 18:42:22 2614 0
1 条回答
写回答
取消 提交回答
  • test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} 
      
    # 输出原始的字典
    print ("字典移除前 : " + str(test_dict)) 
      
    # 使用 del 移除 Zhihu
    del test_dict['Zhihu'] 
      
    # 输出移除后的字典
    print ("字典移除后 : " + str(test_dict)) 
      
    # 移除没有的 key 会报错
    #del test_dict['Baidu']
    执行以上代码输出结果为:
    
    字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
    字典移除后 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
    实例 2 : 使用 pop() 移除
    test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} 
      
    # 输出原始的字典
    print ("字典移除前 : " + str(test_dict)) 
      
    # 使用 pop 移除 Zhihu
    removed_value = test_dict.pop('Zhihu') 
      
    # 输出移除后的字典
    print ("字典移除后 : " + str(test_dict)) 
      
    print ("移除的 key 对应的 value 为 : " + str(removed_value)) 
      
    print ('\r') 
      
    # 使用 pop() 移除没有的 key 不会发生异常,我们可以自定义提示信息
    removed_value = test_dict.pop('Baidu', '没有该键(key)') 
      
    # 输出移除后的字典
    print ("字典移除后 : " + str(test_dict)) 
    print ("移除的值为 : " + str(removed_value))
    执行以上代码输出结果为:
    
    字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
    字典移除后 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
    移除的 key 对应的 value 为 : 4
    
    字典移除后 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
    移除的值为 : 没有该键(key)
    实例 3 : 使用 items() 移除
    test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} 
      
    # 输出原始的字典
    print ("字典移除前 : " + str(test_dict)) 
      
    # 使用 pop 移除 Zhihu
    new_dict = {key:val for key, val in test_dict.items() if key != 'Zhihu'} 
      
      
    # 输出移除后的字典
    print ("字典移除后 : " + str(new_dict))
    执行以上代码输出结果为:
    
    字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
    字典移除后 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
    
    2020-02-14 18:43:00
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载