创建字典
字典是python唯一的一个映射类型
dict1 = {1: "one", 2: "two", 3: "three"}
# 创建一个空字典
dict2 = {}
dict3 = dict()
print(dict3) # {}
# 以元组的形式传入
dict4 = dict(((1, "one"), ))
print(dict4) # {1: 'one'}
# 以元组的形式传入
dict5 = dict(((1, "one"), (2, "two"), (3, "three"))) # {1: 'one', 2: 'two', 3: 'three'}
print(dict5)
# 以列表的形式传入,不过会有提示黄线,python好像不推荐,元组套字典在这里
dict6 = dict(([1, "one"], )) # {1: 'one'}
print(dict6)
# 关键字赋值,如果key等于数字,或是字符串,会报错 SyntaxError: keyword can't be an expression
dict7 = dict(lala="one")
print(dict7) # {'lala': 'one'}
# 直接给关键字赋值
dict7[1] = "one"
print(dict7) # {'lala': 'one', 1: 'one'} 如果key已存在,则覆盖值,没有则添加键值对
dict9 = {6: "se"}
print(dict9.setdefault(6,"six")) # se
print(dict9) # {6: 'se'}
fromkeys()方法
"""
fromkeys(s[,v]) 返回一个新字典 key传入一个可迭代对象,v唯一
"""
dict1 = {}
print(dict1.fromkeys((1,2,3))) # {1: None, 2: None, 3: None}
print(dict1.fromkeys((1,2,3),"num")) # {1: 'num', 2: 'num', 3: 'num'}
print(dict1.fromkeys((1,2,3),("one","two","three")))
# {1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
print(dict1.fromkeys(range(20),"go"))
# {0: 'go', 1: 'go', 2: 'go', 3: 'go', 4: 'go', 5: 'go', 6: 'go', 7: 'go', 8: 'go', 9: 'go', 10: 'go', 11: 'go', 12: 'go', 13: 'go', 14: 'go', 15: 'go', 16: 'go', 17: 'go', 18: 'go', 19: 'go'}
访问字典
keys()
values()
items()
dict1 = dict()
dict1 = dict1.fromkeys(range(10),"go")
for i in dict1.keys():
print(i)
for v in dict1.values():
print(v)
for k,v in dict1.items():
print(k,v)
# 访问单个值
print(dict1[11]) # 如果访问不存在的key,会报错 KeyError: 11
# get方法
print(dict1.get(11)) # None # get方法不会报错,可以设置value,如果不设置,会返回一个None
print(dict1.get(11,"lala")) # lala # 设置会返回传入值
print(dict1.get(9,"lala")) # go # 如果访问已有value的key,贼返回key对应的值,
删除
dict2.clear()------->清空字典
dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}
print(dict1.pop(2)) # two
print(dict1) # {1: 'one', 3: 'three', 4: 'four'}
print(dict1.popitem()) # 随机删除一对键值
print(dict1)
del dict1[1]
print(dict1) # {3: 'three'}
合并字典 update
dict9 = {6: "se"}
dict10 = {10: "ten"}
dict10.update(dict9)
print(dict10) # {10: 'ten', 6: 'se'}