Python 之字典操作

# clear() 清除字典。
# get() ​如果键存在于字典中,则返回该键的值。
# items()​ 返回字典中的键值对列表。
# keys() 返回字典中的键列表。
# values()​ 返回字典中的值列表。
# pop()​ 从字典中删除一个键,如果它存在,并返回它的值。如果存在于字典中,则d.pop()删除并返回其关联值。如果不存在,则引发异常KeyError。
# popitem()​ 从字典中删除键值对。用于删除字典中,最后面的键值对。直到字典被删除至空,则d.popitem()引发KeyError异常。
# update() 把字典参数 dict2 的 key/value(键/值) 对更新到字典 dict 里
# fromkeys() 用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
# setdefault() 方法和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。

if __name__ == '__main__':
    d = {'a': 1, 'b': 2, 'c': 3}
    
    print(d.get('b')) #2

    print(d.items()) #[('a', 1), ('b', 2), ('c', 3)]

    print(d.keys()) #['a', 'b', 'c']

    print(d.values()) #[1, 2, 3]

    print(d.pop('b')) # 2

    print(d) #{'a': 1, 'c': 3}

    print(d.popitem()) # ('c', 3)

    print(d) # {'a': 1}

    d2 = {'d': 4}

    print(d.update(d2))
    print(d) #{'a': 1, 'd': 4}

    print(d2) #{'d': 4}

    d2.clear()
    print(d2) # {}

 

posted @ 2022-10-10 12:11  样子2018  阅读(117)  评论(0编辑  收藏  举报