|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 只为 于 2017-9-3 20:02 编辑
1、dict() 工厂函数(类型)
调用它会生成该类型的一个实例,就像工厂一样,所以称为工程类型
工厂函数还有:str(),int(),list(),tuple()
2、字典的内建方法:
1)创建字典:fromkeys()
| fromkeys(iterable, value=None, /) from builtins.type
| Returns a new dict with keys from iterable and values equal to value.# create
dict1 = {}
print(dict1.fromkeys('1')) # {'1': None}
print(dict1.fromkeys(('1', 38))) # {'1': None, 38: None}
print(dict1.fromkeys(('1', '2'), 'Number')) # {'1': 'Number', '2': 'Number'}
print(dict1.fromkeys(('1', '2'), ('one', 'two', 'three')))
# {'1': ('one', 'two', 'three'), '2': ('one', 'two', 'three')}
注:fromkeys()返回的是一个新的dict,跟原来的没有关系的,上面打印出来的都是匿名的dict,原来的dict1值不变
2) 访问字典的方法:keys(),values(),items()# read
print(dict1) # {}
dict1 = dict1.fromkeys(range(4), 'zan')
print(dict1) # {0: 'zan', 1: 'zan', 2: 'zan', 3: 'zan'}
for eachKey in dict1.keys():
print(eachKey) # 0 1 2 3
for eachValue in dict1.values():
print(eachValue) # zan zan zan zan
for eachItem in dict1.items():
print(eachItem) # (0, 'zan')(1, 'zan')(2, 'zan')(3, 'zan')
3) get() 当不存在key时,可以返回指定的值print(dict1.get(5)) # None
print(dict1.get(5, '木有')) # 木有
4)在字典中检查键的成员资格比序列更加高效,当数据规模相当大的时候,两者的差距会很明显# in not in
print(2 in dict1) # True
print(5 in dict1) # False
print('zan' in dict1) # False
print('zan' in dict1.values()) # True
5)clear():清空字典# clear()
dict1.clear()
print(dict1) # {}
dict1 = {} # 这样情况字典不严谨,不建议这样做(做不到真正的清空), 如下
a = {'小甲鱼': 'name'}
b = a
a = {}
print('a=', a, 'b=', b) # a= {} b= {'小甲鱼': 'name'}
a = {'小甲鱼': 'name'}
b = a
a.clear()
print('a=', a, 'b=', b) # a= {} b= {}
6)copy(): 浅拷贝# copy()
a = {1: 'one', 2: 'two', 3: 'three'}
b = a.copy()
c = a
print('a=', a) # c= {1: 'one', 2: 'two', 3: 'three'}
print('b=', b) # c= {1: 'one', 2: 'two', 3: 'three'}
print('c=', c) # c= {1: 'one', 2: 'two', 3: 'three'}
print(id(a)) # 12007880
print(id(b)) # 12007944
print(id(c)) # 12007880
c[4] = 'four'
print('a=', a) # a= {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
print('b=', b) # b= {1: 'one', 2: 'two', 3: 'three'}
print('c=', c) # c= {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
注:赋值不等于浅拷贝,赋值后的地址不变(指向不变),浅拷贝后的地址是不一样的,只是对对象表层的一个拷贝
7)pop()# pop
print(a.pop(1)) # one
print(a) # {2: 'two', 3: 'three', 4: 'four'}
print # (a.popitem())(2, 'two') 随机返回一个item并删除
print(a) # {3: 'three', 4: 'four'}
8)setdefault()# setdefault()
a.setdefault("小白")
print(a) # {'小白': None, 2: 'two', 3: 'three', 4: 'four'}
a.setdefault(5, 'five')
print(a) # {'小白': None, 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
注:如果已经存在key,再setdefaullt,原dict不变
9)update():利用一个字典或映射关系去更新另一个字典# update()
b = {'小白': '狗'}
a.update(b)
print(a) # {'小白': '狗', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
|
|