码迷,mamicode.com
首页 > 编程语言 > 详细

Python 字典

时间:2019-11-01 18:45:27      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:style   one   一个   ems   输出   set   获取   div   不同   

Python 字典

1. 遍历字典

  • 遍历字典的键
  • dict1 = {a: 1, b: 2, c: 3, d: 4}
    for key in dict1.keys():
        print(key)
    # 输出:a b c d
  • 遍历字典的值
  • dict1 = {a: 1, b: 2, c: 3, d: 4}
    for value in dict1.values():
        print(value)
    dict1.get(a)
    dict1.get(b)
    dict1.get(c)
    # 输出:1 2 3 4
  • 遍历字典的键值对
  • dict1 = {a: 1, b: 2, c: 3, d: 4}
    for k, v in dict1.items():
        print(k, ": ", v)
    # 输出:
    a :  1
    b :  2
    c :  3
    d :  4
  • 更新字典
  • dict1 = {a: 1, b: 2, c: 3, d: 4}
    dict2 = {e: 5}
    dict1.update(dict2)
    print(dict1)
    # 输出:{‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4, ‘e‘: 5}
  • 删除字典所有键值对
  • dict1 = {a: 1, b: 2, c: 3, d: 4, e: 5}
    dict1.clear()
    print(dict1)
    # 输出:{}
  • 删除最后一个键值对
  • dict1 = {a: 1, b: 2, c: 3, d: 4, e: 5}
    dict1.popitem()
    print(dict1)
    # 输出:{‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4}
  • 比较两个字典的差异
  • dict1 = {a: 1, b: 2, c: 3, d: 4}
    dict2 = {a: 1, b: 2, c: 5, e: 6}
    
    differ = set(dict1.items()) ^ set(dict2.items())
    
    """输出所有的差异"""
    print(differ)
    
    # 输出:{(‘c‘, 3), (‘e‘, 6), (‘c‘, 5), (‘d‘, 4)}
    
    """获取两个字典key的交集"""
    diff = dict1.keys() & dict2
    print(diff)
    
    # 输出:{‘a‘, ‘c‘, ‘b‘}
    
    """输出相同key下的不同value"""
    diff_vals = [(k, dict1[k], dict2[k]) for k in diff if dict1[k] != dict2[k]]
    print(diff_vals)
    
    # 输出:[(‘c‘, 3, 5)]
  • 直接赋值何copy的区别

Python 字典

标签:style   one   一个   ems   输出   set   获取   div   不同   

原文地址:https://www.cnblogs.com/swordsman180309/p/11778440.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!