写字典之前出了点小问题
进行dict()创建字典的时候系统给我抛出来了TypeError: dict() object is not callable
仔细看下是上面有个变量不小心用了dict这个关键字导致被覆盖了在namespace下
del(dict)以后就正常运行了
dct = {}
type(dct)
dct_01 = dict(a = 1, b = 2, c = 3)
print(f'利用dict()构造字典{dct_01}')
dct_02 = dict({'a':1,},c=3,d=4)
print(f'键值对 + 关键字参数构造字典{dct_02}')
dct_03 = dict([('a',1),('b',2)])
print(f'迭代对象构造字典:{dct_03}')
dct_04 = {}.fromkeys(['a','b', 'c'], [1, 2, 3])
print(f'fromkeys()方法构造字典{dct_04}')
dct_04_1 = dict({'a':1}.fromkeys(['c','d'],[1,2,3]))
print(f'fromkeys()方法构造字典:{dct_04_1}') # 之前的{}内容将会被覆盖
dct = {'name':'Ding', 'age': 18, 'city': 'BJ', 'yesterday':17,'today':18,'tomorrow':19, 'TEL':(123,456,789)}
for key,val in dct.items():
print(key, val)
# 获取字典对应的集合
type(set(dct))
# 获取字典健的集合
print(set(dct.keys()))
# 获取字典值的集合
print(set(dct.values()))
# 所获取的集合是无先后顺序之分的即字典与集合其实是无序的
# 判断健是否在字典中
print('name 是否是字典dct的健:{}\n'.format('name' in dct))
print('alibaba 是否是字典dct的健: {}'.format('alibaba' in dct))
# 获取某健对应的值
print('age健对应的值为:{}'.format(dct.get('age')))
# 添加或修改一个字典的键值
print(f'原先字典为:{dct}')
dct['GF'] = 'Fantastic'
print(f'添加后:{dct}')
dct['age'] = 18
print(f'修改后:{dct}')
del dct['GF'] # 仅需删除键值
print(f'删除后:{dct}')
try:
rst = dct.pop('TEL')
print('使用dict.pop{}删除得到返回值:'.format(rst))
except:
print("没有这个键值")
# 内容不重复
st = {1,2,1,1,1}
print(f'我以为输入的是\{1,2,1,1,1}实际上是{st}')
# 集合的生成式(列表,元组其实均可)
print('用这种方法也可以生成集合:{}'.format({random.randint(1,100) for i in range(10)}))
st_1 = {random.randint(1,10) for i in range(10)}
st_2 = {random.randint(1,10) for i in range(10)}
# union(返回一个新得集合)
st_union_1and2 = st_1.union(st_2)
print(f'set {st_1} and {st_2} union is {st_union_1and2}')
# difference
st_dif_1to2 = st_1.difference(st_2,{1})
print(f'set {st_1} and {st_2} difference is {st_dif_1to2}')
st_dif_1to2 = st_1.difference(st_2,{3})
print(f'set {st_1} and {st_2} difference is {st_dif_1to2}')
# intersection
st_inters_1and2 = st_1.intersection(st_2)
print(f'set {st_1} and {st_2} intersection is {st_inters_1and2}')
# issubset 子集判断2
print(f'set {st_1} 是 {st_2} 的子集么:' + '{}'.format(st_1.issubset(st_2)))
print('set {0} 是 {1} 的子集么:{2}'.format({1,2}, st_2, {1, 2}.issubset(st_2)))
# 冰冻集合
st = {1,2}
print(st)
st.pop()
print(st)
st.add(3)
print(st)
stf = frozenset(st)
print(type(stf))
try:
stf.add(4)
except:
print('无法改变')
else:
print('骗子根本就不是冰冻集合')
finally:
print(stf)