###1.字典的定义###
"""
总结: 定义字典:
- 定义空字典, {}, dict()
- 赋值: d = {'key':'value', 'key1':'value1'}
- 初始化所有value值: fromkeys()
- 根据已有的数据创建字典:
users = ['user1', 'user2']
passwds = ['123', '456']
zip(users, passwds)
<zip object at 0x7f764d2c3908>
list(zip(users, passwds))
[('user1', '123'), ('user2', '456')]
userinfo = dict(zip(users, passwds))
userinfo
{'user1': '123', 'user2': '456'}
"""
s = {}
print(type(s))
s = {
'fentiao':[100, 80, 90],
'westos':[100,100,100]
}
print(s, type(s))
d = dict()
print(d, type(d))
d = dict(a=1, b=2)
print(d, type(d))
# 随机生成100张卡号, 卡号的格式为610 334455 001 ---610 334455 100
cards = []
for cardId in range(100):
card = "610 334455 %.3d" %(cardId+1)
cards.append(card)
print(cards)
print({}.fromkeys(cards))
print({}.fromkeys(cards, '666666'))
"""
# 定义空集合, 必须set(),
# {}默认的类型为字典;
d = {}
print(type(d))
# 字典: key-value值, 键值对;
# value值可以是任意数据类型: int,float,long, complex, list, tuple,set, dict
d = {
'王旭': [18, '男', "请假"],
'张龙': [18, '男', '俯卧撑']
}
print(d['张龙'])
d2 = {
'a': 1,
'b': 2
}
print(d2)
d3 = {
'a': {1, 2, 3},
'b': {2, 3, 4}
}
print(d3)
# 字典的嵌套;
students = {
'13021001': {
'name':'张龙',
'age':18,
'score':100
},
'13021003': {
'name': '张',
'age': 18,
'score': 90
}
}
print(students['13021003']['name'])
# fromkeys第一个参数可以列表/tuple/str/set, 将列表的每一个元素作为字典的key值,
# 并且所有key的value值一致, 都为'000000';
print({}.fromkeys({'1', '2'}, '000000'))
# 字典必须是不可变数据类型;d = {[1,2,3]:1}(x)
# 可变数据类型:list, set, dict
# 不可变: 数值类型, str, tuple
"""
###2.字典的特性###
# 索引, 切片, 重复, 连接, 成员操作符
d = dict(a=1, b=2)
print(d)
# print(d[0])
# print(d[1:])
# print(d+d)
# print(d*3)
# 成员操作符, 默认判断key值是否存在.
print('a' in d)
print(1 in d)
# for循环: 默认遍历字典的key值;
for i in d:
print(i)
for i,v in enumerate(d):
print(i, '-----', v)
###3.字典的增加###
d = dict(a=1, b=2)
# 添加或者更改key-value对
d['g'] = 10
d['a'] = 10
print(d)
# # update:
# # 如果key值已经存在, 更新value值;
# # 如果key值不存在, 添加key-value值;
# d.update({'a':4, 'f':1})
# print(d)
# # setdefault
# # # 如果key值已经存在, 不做修改;
# # 如果key值不存在, 添加key-value值;默认情况下value值为None
# d.setdefault('g', 10)
# print(d)
###4.字典的删除###
d = dict(a=1, b=2, c=3)
# pop:弹出指定key-value值
# d.pop('a')
# print(d)
# popitem
# d.popitem() ##随机返回并删除字典中的一对键和值(一般删除末尾对)
# print(d)
# del d['a']
# print(d)
d.clear()
print(d)
###5.字典的修改与查看###
services = {
'http':80,
'mysql':3306
}
# 查看字典里面所有的key值
print(services.keys())
# 查看字典里面所有的value值
print(services.values())
# 查看字典里面所有的key-value值
print(services.items())
# 遍历
for k,v in services.items(): # k,v = ('http', 80)
print(k , '--->', v)
for k in services:
print(k, '--->', services[k])
# 查看指定key对应的value值, 注意: key不存在, 就会报错
print(services['http'])
# print(services['https'])
#
# if 'https' in services:
# print(services['https'])
# else:
# print('key not exist')
# get方法获取指定可以对应的value值
# 如果key值存在, 返回对应的value值;
# 如果key值不存在, 默认返回None, 如果需要指定返回的值, 传值即可;
print(services.get('https', 'key not exist'))
###6.通过字典实现列表去重###
# ** 字典的key值是不能重复的.
# d = {'a':1, 'b':2}
# d['a'] = 3
li = [1, 2, 3, 4, 65, 1, 2, 3]
print({}.fromkeys(li).keys())